OpenCV实战1.信用卡数字识别

1. 任务说明

有如下几张信用卡,我们需要根据模板匹配出其中的数字,进行卡号的识别

2. Debug源码

cursor的debug:

launch.json:

bash 复制代码
{
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python 调试程序: 包含参数的当前文件",
            "type": "debugpy",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "args": "${command:pickArgs}"
        },
        {
            "name": "Run OCR Template Matching",
            "type": "debugpy",
            "request": "launch",
            "program": "${workspaceFolder}/template-matching-ocr/ocr_template_match.py",
            "cwd": "${workspaceFolder}",
            "console": "integratedTerminal",
            "args": [
                "-i", "${workspaceFolder}/template-matching-ocr/images/credit_card_01.png",
                "-t", "${workspaceFolder}/template-matching-ocr/ocr_a_reference.png"
            ]
        }
    ]
}

2.1 制作数字模板

这里 -i 选择了第一张信用卡,-t 选择了模板。

python 复制代码
# 导入工具包
import numpy as np
import argparse
import cv2
import myutils

# 设置参数
ap = argparse.ArgumentParser()
# 要匹配的图片
ap.add_argument("-i", "--image", required=True,
	help="path to input image")
# 使用的模板
ap.add_argument("-t", "--template", required=True,
	help="path to template OCR-A image")
args = vars(ap.parse_args())

# 指定信用卡类型
FIRST_NUMBER = {
	"3": "American Express",
	"4": "Visa",
	"5": "MasterCard",
	"6": "Discover Card"
}
# 绘图展示
def cv_show(name,img):
	cv2.imshow(name, img)
	cv2.waitKey(0)
	cv2.destroyAllWindows()
python 复制代码
# 读取一个模板图像
img = cv2.imread(args["template"])
cv_show('img',img)
python 复制代码
# 转换成灰度图
ref = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv_show('ref',ref)

这张图也没啥好转的其实,本身就是这么个图

python 复制代码
# 二值图像
ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1]
cv_show('ref',ref)

轮廓检测 cv2.findContours() 函数接受的参数为二值图,即黑白的(不是灰度图),cv2.RETR_EXTERNAL只检测外轮廓,cv2.CHAIN_APPROX_SIMPLE只保留终点坐标

python 复制代码
# 计算轮廓
# 返回的list中每个元素都是图像中的一个轮廓
contours_info = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
refCnts = contours_info[0] if len(contours_info) == 2 else contours_info[1]
hierarchy = contours_info[1] if len(contours_info) == 2 else contours_info[2]
python 复制代码
cv2.drawContours(img,refCnts,-1,(0,0,255),3) #画一下轮廓refCnts
cv_show('img',img)

-1 表示要画所有的轮廓

打印一下当前shape值:

python 复制代码
print (np.array(refCnts).shape)

(10, ) 10个轮廓

接下来我们需要对轮廓进行一个排序,什么轮廓对应什么数值:

外接矩形的目的是把复杂轮廓压成简单的 (x,y,w,h) 标量信息,以便排序、裁剪、筛选和绘图。

python 复制代码
refCnts = myutils.sort_contours(refCnts, method="left-to-right")[0] #排序,从左到右,从上到下
# 跳转到 myutils.sort_contours
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
    # 对每个轮廓 c 计算一个外接矩形
    boundingBoxes = [cv2.boundingRect(c) for c in cnts] #用一个最小的矩形,把找到的形状包起来x,y,w,h,矩形左上角坐标和宽、高。
    # 进行排序
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
                                        key=lambda b: b[1][i], reverse=reverse))
    # 返回排序完成的轮廓
    return cnts, boundingBoxes

需要把每个轮廓对应的数字匹配起来。

python 复制代码
digits = {}

# 遍历每一个轮廓
for (i, c) in enumerate(refCnts):
	# 计算外接矩形并且resize成合适大小
	(x, y, w, h) = cv2.boundingRect(c)
	# 感兴趣区域roi
	roi = ref[y:y + h, x:x + w]
	# 把这个框resize成合适大小
	roi = cv2.resize(roi, (57, 88))
	# 每一个数字对应每一个抠出来的模板
	digits[i] = roi

# 最后得出每个数字的模板

2.2 对输入图像做处理

原始图像:

想要找到其中的带字的区域。

python 复制代码
# 初始化卷积核
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

# 读取输入图像,预处理
image = cv2.imread(args["image"])
cv_show('image',image)
image = myutils.resize(image, width=300)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv_show('gray',gray)

# 礼帽操作,突出更明亮(字体)的区域
tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel) 
cv_show('tophat',tophat) 

再找出这些亮区的边缘/梯度(Sobel):

python 复制代码
# 突出这些亮区在 x 方向的强烈强度变化(通常对应垂直边缘)。
# ksize=-1 在 OpenCV 中表示用 Scharr 算子(不是简单的 3×3 Sobel),对细节/小结构的微小变化更敏感。
gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)
gradX = np.absolute(gradX) # 取绝对值,保留梯度强度
(minVal, maxVal) = (np.min(gradX), np.max(gradX))
gradX = (255 * ((gradX - minVal) / (maxVal - minVal))) # 将梯度线性归一化到 [0,255] 并转回 uint8。
gradX = gradX.astype("uint8")

print (np.array(gradX).shape)
cv_show('gradX',gradX)

为了便于后续找轮廓和识别,我们希望把号码分成4块,怎么能让每一块中的数字连在一起,先膨胀,在腐蚀:

python 复制代码
#通过闭操作(先膨胀,再腐蚀)将数字连在一起
gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel) 
cv_show('gradX',gradX)
python 复制代码
#THRESH_OTSU会自动寻找合适的阈值,适合双峰,需把阈值参数设置为0
thresh = cv2.threshold(gradX, 0, 255,
	cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] 
cv_show('thresh',thresh)

目前还不够完美,白色区域内还有黑块,需要填起来

python 复制代码
#再来一个闭操作,作用是填补小孔、连通相近的白色区域。
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel)
cv_show('thresh',thresh)
python 复制代码
# 计算轮廓
# cv2.RETR_EXTERNAL:只返回外部轮廓;cv2.CHAIN_APPROX_SIMPLE:对轮廓点做压缩
contours_info = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
threshCnts = contours_info[0] if len(contours_info) == 2 else contours_info[1]
hierarchy = contours_info[1] if len(contours_info) == 2 else contours_info[2]

# 绘制轮廓
cnts = threshCnts
cur_img = image.copy()
cv2.drawContours(cur_img,cnts,-1,(0,0,255),3) 
cv_show('img',cur_img)
python 复制代码
# 想要的区域
locs = []

# 遍历轮廓
for (i, c) in enumerate(cnts):
	# 计算矩形
	(x, y, w, h) = cv2.boundingRect(c)
	ar = w / float(h)
	# 选择合适的区域,根据实际任务来,这里的基本都是四个数字一组
	if ar > 2.5 and ar < 4.0:
		if (w > 40 and w < 55) and (h > 10 and h < 20):
			#符合的留下来
			locs.append((x, y, w, h))
# 将符合的轮廓从左到右排序
locs = sorted(locs, key=lambda x:x[0])

一共四组需要的轮廓:

我们做匹配肯定不能拿大轮廓去做匹配,应该是大轮廓分成4个小轮廓,然后和模板去匹配。

python 复制代码
output = []
# 遍历每一个轮廓中的数字
for (i, (gX, gY, gW, gH)) in enumerate(locs):
	# initialize the list of group digits
	groupOutput = []

	# 根据坐标提取每一个组
	group = gray[gY - 5:gY + gH + 5, gX - 5:gX + gW + 5] # 稍微拿大一点
	cv_show('group',group)
python 复制代码
	# 对轮廓进行预处理,二值化
	group = cv2.threshold(group, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
	cv_show('group',group)
	# 计算每一组的轮廓,还是计算+排序
	contours_info = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
	digitCnts = contours_info[0] if len(contours_info) == 2 else contours_info[1]
	hierarchy = contours_info[1] if len(contours_info) == 2 else contours_info[2]
	digitCnts = myutils.sort_contours(digitCnts, method="left-to-right")[0]

	# 计算每一组中的4个小轮廓的每一个数值
	for c in digitCnts:
		# 找到当前数值的轮廓,resize成合适的的大小
		(x, y, w, h) = cv2.boundingRect(c) # 外接矩形
		roi = group[y:y + h, x:x + w]
		roi = cv2.resize(roi, (57, 88)) # 和之前做的模板是一样的
		cv_show('roi',roi)
python 复制代码
		# 计算匹配得分,跟模板中的数进行匹配
		scores = []

		# 在模板中计算与每一个模板(0123456789)的得分
		for (digit, digitROI) in digits.items():
			# 模板匹配
			result = cv2.matchTemplate(roi, digitROI, cv2.TM_CCOEFF)
			(_, score, _, _) = cv2.minMaxLoc(result)
			scores.append(score)
		# 最终score中有10个值
		# 得到最合适的数字
		groupOutput.append(str(np.argmax(scores)))
	# 把所有小轮廓都匹配好
	
	# 画出来
	cv2.rectangle(image, (gX - 5, gY - 5),
		(gX + gW + 5, gY + gH + 5), (0, 0, 255), 1)
	cv2.putText(image, "".join(groupOutput), (gX, gY - 15),
		cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 255), 2)

	# 得到结果
	output.extend(groupOutput)
	# 一个大轮廓就结束了
# 所有大轮廓都结束了,都放到output中了
python 复制代码
# 打印结果
print("Credit Card Type: {}".format(FIRST_NUMBER[output[0]]))
print("Credit Card #: {}".format("".join(output)))
cv2.imshow("Image", image)
cv2.waitKey(0)