OpenCV-Python身份证信息识别
本篇文章使用OpenCV-Python和CnOcr来实现身份证信息识别的案例。想要识别身份证中的文本信息,总共分为三大步骤:一、通过预处理身份证区域检测查找;二、身份证文本信息提取;三、身份证文本信息识别。下面来看一下识别的具体过程CnOcr官网。识别过程视频
前置环境
这里的环境需要安装OpenCV-Python,Numpy和CnOcr。本篇文章使用的Python版本为3.6,OpenCV-Python版本为3.4.1.15,如果是4.x版本的同学,可能会有一些Api操作不同。这些依赖的安装和介绍,我就不在这里赘述了,均是使用Pip进行安装。
识别过程
首先,导入所需要的依赖cv2,numpy,cnocr并创建一个show图像的函数,方便后面使用:
import cv2
import numpy as np
from cnocr import CnOcr
def show(image, window_name):
cv2.namedWindow(window_name, 0)
cv2.imshow(window_name, image)
cv2.waitKey(0)
cv2.destroyAllWindows()
ocr = CnOcr(model_name='densenet_lite_136-gru')
身份证区域查找
通过对加载图像的灰度处理–>滤波处理–>二值处理–>边缘检测–>膨胀处理–>轮廓查找–>透视变换(校正)–>图像旋转–>固定图像大小一系列处理之后,我们便可以清晰的裁剪出身份证的具体区域。
原始图像
使用OpenCV的imread方法读取本地图片。
image = cv2.imread('card.png')
show(image, "image")
灰度处理
将三通道BGR图像转化为灰度图像,因为一下OpenCV操作都是需要基于灰度图像进行的。
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
show(gray, "gray")
中值滤波
使用滤波处理,也就是模糊处理,这样可以减少一些不需要的噪点。
blur = cv2.medianBlur(gray, 7)
show(blur, "blur")
二值处理
二值处理,非黑即白。这里通过cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU,使用OpenCV的大津法二值化,对图像进行处理,经过处理后的图像,更加清晰的分辨出了背景和身份证的区域。
threshold = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
show(threshold, "threshold")
边缘检测
使用OpenCV中最常用的边缘检测方法,Canny,检测出图像中的边缘。
canny = cv2.Canny(threshold, 100, 150)
show(canny, "canny")
边缘膨胀
为了使上一步边缘检测的边缘更加连贯,使用膨胀处理,对白色的边缘膨胀,即边缘线条变得更加粗一些。
kernel = np.ones((3, 3), np.uint8)
dilate = cv2.dilate(canny, kernel, iterations=5)
show(dilate, "dilate")
轮廓检测
使用findContours对边缘膨胀过的图片进行轮廓检测,可以清晰的看到背景部分还是有很多噪点的,所需要识别的身份证部分也被轮廓圈了起来。
binary, contours, hierarchy = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
image_copy = image.copy()
res = cv2.drawContours(image_copy, contours, -1, (255, 0, 0), 20)
show(res, "res")
轮廓排序
经过对轮廓的面积排序,我们可以准确的提取出身份证的轮廓。
contours = sorted(contours, key=cv2.contourArea, reverse=True)[0]
image_copy = image.copy()
res = cv2.drawContours(image_copy, contours, -1, (255, 0, 0), 20)
show(res, "contours")
透视变换
通过对轮廓近似提取出轮廓的四个顶点,并按顺序进行排序,之后通过warpPerspective对所选图像区域进行透视变换,也就是对所选的图像进行校正处理。
epsilon = 0.02 * cv2.arcLength(contours, True)
approx = cv2.approxPolyDP(contours, epsilon, True)
n = []
for x, y in zip(approx[:, 0, 0], approx[:, 0, 1]):
n.append((x, y))
n = sorted(n)
sort_point = []
n_point1 = n[:2]
n_point1.sort(key=lambda x: x[1])
sort_point.extend(n_point1)
n_point2 = n[2:4]
n_point2.sort(key=lambda x: x[1])
n_point2.reverse()
sort_point.extend(n_point2)
p1 = np.array(sort_point, dtype=np.float32)
h = sort_point[1][1] - sort_point[0][1]
w = sort_point[2][0] - sort_point[1][0]
pts2 = np.array([[0, 0], [0, h], [w, h], [w, 0]], dtype=np.float32)
M = cv2.getPerspectiveTransform(p1, pts2)
dst = cv2.warpPerspective(image, M, (w, h))
show(dst, "dst")
固定图像大小
将图像变正,通过对图像的宽高进行判断,如果宽
Original: https://blog.csdn.net/wFitting/article/details/124039827
Author: wFitting
Title: OpenCV-Python身份证信息识别
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/519128/
转载文章受原作者版权保护。转载请注明原作者出处!