php使用OpenCV实现从照片中截取身份证区域照片

发布时间:2023年12月18日

<?php
// 获取上传的文件
$file = $_FILES['file'];

// 获取文件的临时名称
$tmp_name = $file['tmp_name'];

// 获取文件的类型
$type = $file['type'];

// 获取文件的大小
$size = $file['size'];

// 获取文件的错误信息
$error = $file['error'];

// 检查文件是否上传成功
if ($error!== UPLOAD_ERR_OK) {
? ? echo "文件上传失败:{$error}";
? ? exit;
}

// 检查文件是否为图像文件
if (!in_array($type, ['image/jpeg', 'image/png'])) {
? ? echo "文件不是图像文件";
? ? exit;
}

// 加载图像文件
switch ($type) {
? ? case 'image/jpeg':
? ? ? ? $image = cv\imread($tmp_name, cv\IMREAD_COLOR);
? ? ? ? break;
? ? case 'image/png':
? ? ? ? $image = cv\imread($tmp_name, cv\IMREAD_COLOR);
? ? ? ? break;
}

// 检查是否成功加载图像
if ($image === false) {
? ? echo "无法加载图像";
? ? exit;
}

// 定义身份证区域的坐标
$x1 = $y1 = $x2 = $y2 = null;

// 使用OpenCV来识别身份证区域
$gray = cv\cvtColor($image, cv\COLOR_BGR2GRAY);
$thresh = cv\threshold($gray, 0, 255, cv\THRESH_BINARY_INV + cv\THRESH_OTSU)[1];
$contours = cv\findContours($thresh, cv\RETR_EXTERNAL, cv\CHAIN_APPROX_SIMPLE);
foreach ($contours as $contour) {
? ? $area = cv\contourArea($contour);
? ? if ($area > 1000 && $area < 10000) {
? ? ? ? $rect = cv\boundingRect($contour);
? ? ? ? if ($x1 === null) {
? ? ? ? ? ? $x1 = $rect[0];
? ? ? ? ? ? $y1 = $rect[1];
? ? ? ? ? ? $x2 = $rect[0] + $rect[2];
? ? ? ? ? ? $y2 = $rect[1] + $rect[3];
? ? ? ? } else {
? ? ? ? ? ? $x1 = min($x1, $rect[0]);
? ? ? ? ? ? $y1 = min($y1, $rect[1]);
? ? ? ? ? ? $x2 = max($x2, $rect[0] + $rect[2]);
? ? ? ? ? ? $y2 = max($y2, $rect[1] + $rect[3]);
? ? ? ? }
? ? }
}

// 检查是否成功找到身份证区域
if ($x1 === null || $x2 === null || $y1 === null || $y2 === null) {
? ? echo "无法找到身份证区域";
? ? exit;
}

// 裁剪身份证区域
$crop = cv\crop($image, $x1, $y1, $x2 - $x1, $y2 - $y1);

// 生成裁剪后的图像文件
switch ($type) {
? ? case 'image/jpeg':
? ? ? ? cv\imwrite('identity_card.jpg', $crop);
? ? ? ? break;
? ? case 'image/png':
? ? ? ? cv\imwrite('identity_card.png', $crop);
? ? ? ? break;
}

// 释放内存
cv\destroyAllWindows();

echo "身份证区域已裁剪并保存为identity_card.jpg或identity_card.png";
?>
?

文章来源:https://blog.csdn.net/dumingming_stj/article/details/134967217
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。