飞道的博客

Python+Opencv身份证号码区域提取及识别

517人阅读  评论(0)

前端时间智能信息处理实训,我选择的课题为身份证号码识别,对中华人民共和国公民身份证进行识别,提取并识别其中的身份证号码,将身份证号码识别为字符串的形式输出。现在实训结束了将代码发布出来供大家参考,识别的方式并不复杂,并加了一些注释,如果有什么问题可共同讨论。最后重要的事情说三遍:请勿直接抄袭,请勿直接抄袭,请勿直接抄袭!尤其是我的学弟学妹们,还是要自己做的,小心直接拿我的用被老师发现了挨批^_^。


实训环境:CentOS-7.5.1804 + Python-3.6.6 + Opencv-3.4.1

做测试用的照片以及数字识别匹配使用的模板(自制)提供给大家,通过查询得到,身份证号码使用的字体格式为OCR-B 10 BT格式,实训中用到的身份证图片为训练测试图片,有一部分是老师当时直接给出的,还有一部分是我自己用自己身份证做的测试和从网上找到了一张,由于部分身份证号码不是标准字体格式,对识别造成影响,所以有部分图片我还提前ps了一下。

01
02
03
模板

流程图

流程图

前期处理的部分不在描述,流程图和代码注释中都有。其实整个过程并不是很复杂,本来想过在数字识别方面用现成的一些方法,或者想要尝试用到卷积神经网络(CNN)然后做训练集来识别。后来在和老师交流的时候,老师给出建议可以尝试使用特征点匹配或者其他类方法。根据最后数字分割出来单独显示的效果,想到了一个适合于我代码情况的简单方法。

建立一个标准号码库(利用上面自制模板数字分割后获得),然后用每一个号码图片与库中所有标准号码图片做相似度匹配,和哪一个模板相似度最高,则说明该图片为哪一位号码。在将模板号码分割成功后,最关键的一步就是进行相似度匹配。为提高匹配的精确度和效率,首先利用cv.resize()将前面被提取出的每位身份证号码以及标准号码库中的号码做图像大小调整,统一将图像均调整为12x18像素的大小,图像大小的选择是经过慎重的考虑的,如果太大则计算过程耗时,如果过小则可能存在较大误差。匹配的具体方案为:记录需要识别的图片与每个模板图片中有多少位置的像素点相同,相同的越多,说明相似度越高,也就最有可能是某个号码。最终将18位号码都识别完成后,得到的具体的相似度矩阵。

具体代码如下所示:


  
  1. import cv 2 as cv
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. # 将身份证号码区域从身份证中提取出
  5. def Extract(op_image, sh_image):
  6. binary, contours, hierarchy = cv.findContours(op_image,
  7. cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
  8. contours.remove(contours[ 0])
  9. max_x, max_y, max_w, max_h = cv.boundingRect(contours[ 0])
  10. color = ( 0, 0, 0)
  11. for c in contours:
  12. x, y, w, h = cv.boundingRect(c)
  13. cv.rectangle(op_image, (x, y), (x + w, y + h), color, 1)
  14. cv.rectangle(sh_image, (x, y), (x + w, y + h), color, 1)
  15. if max_w < w:
  16. max_x = x
  17. max_y = y
  18. max_w = w
  19. max_h = h
  20. cut_img = sh_image[max_y:max_y+max_h, max_x:max_x+max_w]
  21. cv.imshow( "The recognized enlarged image", op_image)
  22. cv.waitKey( 0)
  23. cv.imshow( "The recognized binary image", sh_image)
  24. cv.waitKey( 0)
  25. return cut_img
  26. # 号码内部区域填充(未继续是用此方法)
  27. def Area_filling(image, kernel):
  28. # The boundary image
  29. iterate = np.zeros(image.shape, np.uint 8)
  30. iterate[:, 0] = image[:, 0]
  31. iterate[:, - 1] = image[:, - 1]
  32. iterate[ 0, :] = image[ 0, :]
  33. iterate[- 1, :] = image[- 1, :]
  34. while True:
  35. old_iterate = iterate
  36. iterate_dilation = cv.dilate(iterate, kernel, iterations= 1)
  37. iterate = cv.bitwise_and(iterate_dilation, image)
  38. difference = cv.subtract(iterate, old_iterate)
  39. # if difference is all zeros it will return False
  40. if not np.any(difference):
  41. break
  42. return iterate
  43. # 将身份证号码区域再次切割使得一张图片一位号码
  44. def Segmentation(cut_img, kernel, n):
  45. #首先进行一次号码内空白填充(效果不佳,放弃)
  46. #area_img = Area_filling(cut_img, kernel)
  47. #cv.imshow("area_img", area_img)
  48. #cv.waitKey(0)
  49. #dilate = cv.dilate(area_img, kernel, iterations=1)
  50. #cv.imshow("dilate", dilate)
  51. #cv.waitKey(0)
  52. cut_copy = cut_img.copy()
  53. binary, contours, hierarchy = cv.findContours(cut_copy, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
  54. contours.remove(contours[ 0])
  55. for c in contours:
  56. x, y, w, h = cv.boundingRect(c)
  57. for i in range(h):
  58. for j in range(w):
  59. # 把首次用findContours()方法识别的轮廓内区域置黑色
  60. cut_copy[y + i, x + j] = 0
  61. # cv.rectangle(cut_copy, (x, y), (x + w, y + h), color, 1)
  62. cv.imshow( "Filled image", cut_copy)
  63. cv.waitKey( 0)
  64. # 尝试进行分割
  65. binary, contours, hierarchy = cv.findContours(cut_copy, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
  66. #tmp_img = cut_img.copy()
  67. # 如果识别的轮廓数量不是n+1位(首先是一个整个区域的轮廓,然后是n位号码各自的轮廓,身份证和匹配模板分割均用此方法)
  68. while len(contours)!=n+ 1:
  69. if len(contours) < n+ 1:
  70. # 如果提取的轮廓数量小于n+1, 说明可能有两位数被识别到一个轮廓中,做一次闭运算,消除数位之间可能存在的连接部分,然后再次尝试提取
  71. #cut_copy = cv.dilate(cut_copy, kernel, iterations=1)
  72. cut_copy = cv.morphologyEx(cut_copy, cv.MORPH_CLOSE, kernel)
  73. cv.imshow( "cut_copy", cut_copy)
  74. cv.waitKey( 0)
  75. # 再次尝试提取身份证区域的轮廓并将轮廓内区域用黑色覆盖
  76. binary, contours, hierarchy = cv.findContours(cut_copy, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
  77. # 去掉提取出的第一个轮廓(第一个轮廓为整张图片)
  78. contours.remove(contours[ 0])
  79. for c in contours:
  80. x, y, w, h = cv.boundingRect(c)
  81. for i in range(h):
  82. for j in range(w):
  83. cut_copy[y + i, x + j] = 0
  84. # cv.rectangle(cut_copy, (x, y), (x + w, y + h), color, 1)
  85. cv.imshow( "Filled image", cut_copy)
  86. cv.waitKey( 0)
  87. #如果findContours()结果为n,跳出
  88. if len(contours) == n:
  89. break
  90. elif len(contours) > n+ 1:
  91. # 如果提取的轮廓数量大于n+1, 说明可能有一位数被识别到两个轮廓中,做一次开运算,增强附近身份证区域部分之间的连接部分,然后再次尝试提取
  92. #cut_copy = cv.erode(cut_copy, kernel, iterations=1)
  93. cut_copy = cv.morphologyEx(cut_copy, cv.MORPH_OPEN, kernel 2)
  94. cv.imshow( "cut_copy", cut_copy)
  95. cv.waitKey( 0)
  96. #再次尝试提取身份证区域的轮廓并将轮廓内区域用黑色覆盖
  97. binary, contours, hierarchy = cv.findContours(cut_copy, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
  98. #去掉提取出的第一个轮廓(第一个轮廓为整张图片)
  99. contours.remove(contours[ 0])
  100. for c in contours:
  101. x, y, w, h = cv.boundingRect(c)
  102. for i in range(h):
  103. for j in range(w):
  104. cut_copy[y + i, x + j] = 0
  105. # cv.rectangle(cut_copy, (x, y), (x + w, y + h), color, 1)
  106. #cv.imshow("cut_copy", cut_copy)
  107. #cv.waitKey(0)
  108. if len(contours) == n:
  109. break
  110. # 上述while()中循环完成后,处理的图像基本满足分割要求,进行最后的提取分割
  111. binary, contours, hierarchy = cv.findContours(cut_copy, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
  112. contours.remove(contours[ 0])
  113. color = ( 0, 0, 0)
  114. for c in contours:
  115. x, y, w, h = cv.boundingRect(c)
  116. for i in range(h):
  117. for j in range(w):
  118. cv.rectangle(cut_copy, (x, y), (x + w, y + h), color, 1)
  119. cv.rectangle(cut_img, (x, y), (x + w, y + h), color, 1)
  120. cv.imshow( "Filled image", cut_copy)
  121. cv.waitKey( 0)
  122. cv.imshow( "cut_img", cut_img)
  123. cv.waitKey( 0)
  124. #print('number:', len(contours))
  125. # Returns the result of the split
  126. return contours
  127. #return cut_img
  128. # Sort排序方法,先将图像分割,由于分割的先后顺序不是按照从左往右,根据横坐标大小将每位身份证号码图片进行排序
  129. def sort(contours, image):
  130. tmp_num = []
  131. x_all = []
  132. x_sort = []
  133. for c in contours:
  134. x, y, w, h = cv.boundingRect(c)
  135. # 使用x坐标来确定身份证号码图片的顺序,把个图片坐标的x值放入x_sort中
  136. x_sort.append(x)
  137. # 建立一个用于索引x坐标的列表
  138. x_all.append(x)
  139. tmp_img = image[y+ 1:y+h- 1, x+ 1:x+w- 1]
  140. tmp_img = cv.resize(tmp_img, ( 40, 60))
  141. cv.imshow( "Number", tmp_img)
  142. cv.waitKey( 0)
  143. # 将分割的图片缩小至12乘18像素的大小,标准化同时节约模板匹配的时间
  144. tmp_img = cv.resize(tmp_img, ( 12, 18))
  145. tmp_num.append(tmp_img)
  146. # 利用x_sort排序,用x_all索引,对身份证号码图片排序
  147. x_sort.sort()
  148. num_img = []
  149. for x in x_sort:
  150. index = x_all.index(x)
  151. num_img.append(tmp_num[index])
  152. # 返回排序后图片列表
  153. return num_img
  154. # 图像识别方法
  155. def MatchImage(img_num, tplt_num):
  156. # IDnum用于存储最终的身份证字符串
  157. IDnum = ''
  158. # 身份证号码18位
  159. for i in range( 18):
  160. # 存储最大相似度模板的索引以及最大相似度
  161. max_index = 0
  162. max_simil = 0
  163. # 模板有1~9,0,X共11个
  164. for j in range( 11):
  165. # 存储身份证号码图片与模板之间的相似度
  166. simil = 0
  167. for y in range( 18):
  168. for x in range( 12):
  169. # 如果身份证号码图片与模板之间对应位置像素点相同,simil 值自加1
  170. if img_num[i][y,x] == tplt_num[j][y,x]:
  171. simil+= 1
  172. if max_simil < simil:
  173. max_index = j
  174. max_simil = simil
  175. print(str(simil)+' ',end='')
  176. if max_index < 9:
  177. IDnum += str(max_index+ 1)
  178. elif max_index == 9:
  179. IDnum += str( 0)
  180. else:
  181. IDnum += 'X'
  182. print()
  183. return IDnum
  184. # 最终效果展示
  185. def display(IDnum, image):
  186. image = cv.resize(image, ( 960, 90))
  187. plt.figure(num='ID_Number')
  188. plt.subplot( 111), plt.imshow(image, cmap='gray'), plt.title(IDnum, fontsize= 30), plt.xticks([]), plt.yticks([])
  189. plt.show()
  190. if __name__ == '__main__':
  191. # 一共三张做测试用身份证图像
  192. path = 'IDcard 01.jpg'
  193. #path = 'IDcard02.png'
  194. #path = 'IDcard.jpg'
  195. id_card = cv.imread(path, 0)
  196. cv.imshow('Original image', id_card)
  197. cv.waitKey( 0)
  198. # 将图像转化成标准大小
  199. id_card = cv.resize(id_card,( 1200, 820))
  200. cv.imshow('Enlarged original image', id_card)
  201. cv.waitKey( 0)
  202. # 图像二值化
  203. ret, binary_img = cv.threshold(id_card, 127, 255, cv.THRESH_BINARY)
  204. cv.imshow('Binary image', binary_img)
  205. cv.waitKey( 0)
  206. # RECTANGULAR
  207. kernel = cv.getStructuringElement(cv.MORPH_RECT, ( 3, 3))
  208. # RECTANGULAR
  209. kernel2 = cv.getStructuringElement(cv.MORPH_DILATE, ( 5, 5))
  210. #close_img = cv.morphologyEx(binary_img, cv.MORPH_CLOSE, kernel)
  211. # The corrosion treatment connects the ID Numbers
  212. erode = cv.erode(binary_img, kernel, iterations= 10)
  213. cv.imshow('Eroded image', erode)
  214. cv.waitKey( 0)
  215. cut_img = Extract(erode, binary_img.copy())
  216. cv.imshow( "cut_img", cut_img)
  217. cv.waitKey( 0)
  218. # 存储最终分割的轮廓
  219. contours = Segmentation(cut_img, kernel, 18)
  220. # 对图像进行分割并排序
  221. img_num = sort(contours, cut_img)
  222. # 识别用的模板
  223. tplt_path = '/home/image/Pictures/template.jpg'
  224. tplt_img = cv.imread(tplt_path, 0)
  225. #cv.imshow('Template image', tplt_img)
  226. #cv.waitKey(0)
  227. ret, binary_tplt = cv.threshold(tplt_img, 127, 255, cv.THRESH_BINARY)
  228. cv.imshow('Binary template image', binary_tplt)
  229. cv.waitKey( 0)
  230. # 与身份证相同的分割方式
  231. contours = Segmentation(binary_tplt, kernel, 11)
  232. tplt_num = sort(contours, binary_tplt)
  233. # 最终识别出的身份证号码
  234. IDnum = MatchImage(img_num, tplt_num)
  235. print('\nID_Number is:', IDnum)
  236. # 图片展示
  237. display(IDnum, cut_img)

效果展示:

 


转载:https://blog.csdn.net/l870358133/article/details/107352594
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场