©FuXianjun
案例要求
提供一张信用卡图像,通过图像处理识别出信用卡上的数字。
代码实现:
1.对模板图片进行处理,得到每个数字的模板。
import cv2
import numpy as np
def cv_show(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def sort_contours(cnts, method="left-to-right"):
reverse = False
i = 0
if method == "right-to-left" or method == "bottom-to-top":
reverse = True
if method == "top-to-bottom" or method == "bottom-to-top":
i = 1
boundingBoxes = [cv2.boundingRect(c) for c in cnts] #用一个最小的矩形,把找到的形状包起来x,y,h,w
(cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
key=lambda b: b[1][i], reverse=reverse))
return cnts, boundingBoxes
# 读取模板图片
template = cv2.imread('ocr_a_reference.png')
cv_show('template', template)
# 模板图片灰度化。这里的模板图片本身就是二值化的因此没有明显区别。
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
cv_show('templage_gray', template_gray)
# 二值化,转化为数字为白色,背景为黑色的图片。
template_binary = cv2.threshold(template_gray, 127, 255, cv2.THRESH_BINARY_INV)[1]
cv_show('template_binary', template_binary)
运行结果
这里threshold后面的[1]表示取threshold函数返回值的第二个。threshold函数返回值为阈值和二值化后的图片,即这里仅保存返回后的图片。
# 根据二值化的模板图,进行轮廓检测
cnts, hierarchy = cv2.findContours(template_binary
, cv2.RETR_EXTERNAL
, cv2.CHAIN_APPROX_SIMPLE)
# 画出每个数字的轮廓
template_rect = cv2.drawContours(templat