python_opencv--身份证文字区域检测
概述
本文基于opencv的形态学滤波检测身份证上的文字位置。
如果是自然场景的文字检测可以用CTPN或者EAST。我这里是身份证合成照片,没有多余背景,也没有复杂光照,所以就用最简单的办法。
代码
import sys
import numpy as np
import cv2
def test_detect (img_path):
# 参考:https://blog.****.net/it2153534/article/details/79185397
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
# 二值化图片
ret,th=cv2.threshold(img,100,255,cv2.THRESH_BINARY)
kernel = np.ones((10,20),np.uint8)
# 开运算
closing = cv2.morphologyEx(th, cv2.MORPH_OPEN, kernel)
# 腐蚀
kernel = np.ones((5,10),np.uint8)
dilation = cv2.erode(closing,kernel,iterations = 1)
# 查找和筛选文字区域
region = []
# 查找轮廓
img2, contours, hierarchy = cv2.findContours(dilation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 利用以上函数可以得到多个轮廓区域,存在一个列表中。
# 筛选那些面积小的
for i in range(len(contours)):
# 遍历所有轮廓
# cnt是一个点集
cnt = contours[i]
# 计算该轮廓的面积
area = cv2.contourArea(cnt)
# 面积小的都筛选掉、这个300可以按照效果自行设置
if(area < 300):
continue
# 找到最小的矩形,该矩形可能有方向
rect = cv2.minAreaRect(cnt)
# 打印出各个矩形四个点的位置
print ("rect is: ")
print (rect)
# box是四个点的坐标
box = cv2.boxPoints(rect)
box = np.int0(box)
# 计算高和宽
height = abs(box[0][1] - box[2][1])
width = abs(box[0][0] - box[2][0])
# 筛选那些太细的矩形,留下扁的
if(height > width ):
continue
region.append(box)
color = cv2.cvtColor(dilation, cv2.COLOR_GRAY2RGB)
for box in region:
cv2.drawContours(color, [box], 0, (0, 0, 255), 2)
cv2.imshow('gray', color)
cv2.waitKey(0)#无限期等待输入
if __name__ == '__main__':
# test_detect('imgs/182019010306541866.png')
test_detect('imgs/182019010306381896.png')
效果:
照片的位置比较固定,可以用坐标范围过滤掉照片上的那个框。