CV

opencv项目实战-数字信用卡识别

python-opencv实现,计算机视觉知识体系,包含轮廓检测、阈值处理、模板匹配等。

Posted by LJJ on September 24, 2019

数字信用卡识别

前言

  • 项目内容来自网络上。
  • 我在学习机器视觉相关知识时,看论文和别人的项目很多都基于Opencv,于是学习opencv的相关知识和用法,希望通过几个实战项目来提高自己的水平。当然,有数字图像处理和部分opencv-python的基础,这是开始的前提。

  • 项目采用的主要方法是轮廓检测和模板匹配,运用了图像处理基础知识来完成。

Method

信用卡上的数字是怎么识别出来的呢?有以下一定的流程:

  1. 数据准备
    • 获取与信用卡上数字相同的数字模板
  2. 对数字模板进行处理
    • 转化为灰度图
    • 转化为二值图像
    • 计算数字图像每个数字外轮廓
    • 对轮廓信息进行排序使其恢复到对应的顺序
    • 根据轮廓获得外接矩形
    • 将外接矩形放缩到一定大小
    • 映射每一个数字模板到数字
  3. 对待识别信用卡图像进行处理
    • 缩放图像到适当大小
    • 转化为灰度图
    • 对图像做顶帽操作,突出明亮区域
    • 用Sobel算子做梯度处理
    • 对图像进行闭操作
    • 对图像进行阈值处理
    • 计算图像轮廓并排序
  4. 模板匹配
    • 找出信用卡图像数值轮廓
    • 放缩成合适大小
    • 计算每个模板匹配得分
    • 得到匹配得分最高的数字
  5. 显现对比
    • 在原待识别信用卡图像上画出对应数字

关键函数

  • cv2.waitKey(0)
  • cv2.destroyAllWindows()

waitKey()是窗口显现等待时间设置,传入参数0则有键盘按下就自动退出窗口。

  • cv2.threshold()
  • cv2.threshold(src, thresh, maxval, type[, dst]) → retval, dstv
cv2.threshold(src, thresh, maxval, type[, dst]) → retval, dst
@param: src – input array (single-channel, 8-bit or 32-bit floating point).
@param: thresh – threshold value. 因为是固定阈值分割,所以必须选择一个固定的值作为分界线
@param: maxval – 在使用THRESH_BINARY和THRESH_BINARY_INV的时候,需要指定最大值
                maximum value to use with the THRESH_BINARY and
                THRESH_BINARY_INV thresholding types.
@param: type – thresholding type (see the details below).

用来实现阈值分割,retreturn value缩写,代表当前的阈值。其函数定义如下

.

  • cv2.findContours()

函数的三个参数,第一个是原图,第二个是轮廓获取方式,第三个是轮廓近似方法。它会输出图片,轮廓和层级。轮廓是Python的列表,包括了图片里的所有轮廓,每个轮廓是一个Numpy的数组,包含对象的边界点的坐标(x,y)。

  • drawContours(img,contours,-1,(0,255,0),3)

用来绘制轮廓,它的第一个参数是原图,第二个参数是图形的轮廓,应该传一个Python列表,第三个参数是轮廓索引(在绘制特定的轮廓的时候有用,要画所有的就传-1)剩下的参数是颜色,厚度等。

  • zip(*a )

函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

  • cv2.matchTemplate()

模板匹配,匹配函数返回的是一副灰度图,最白的地方表示最大的匹配。使用cv2.minMaxLoc()函数可以得到最大匹配值的坐标,以这个点为左上角角点,模板的宽和高画矩形就是匹配的位置。

  • cv2.morphologyEx(img, type, kernel)

形态学运算,根据type的不同,有顶帽,开,闭、黑帽等。

  • cv2.getStructuringElement( )

返回指定形状和尺寸的结构元素。函数的第一个参数表示内核的形状,有三种形状可以选择。

矩形:MORPH_RECT;

交叉形:MORPH_CROSS;

椭圆形:MORPH_ELLIPSE;

第二和第三个参数分别是内核的尺寸以及锚点的位置。

  • cv2.boundingRect(cnt)

得到最小外接矩形。返回四个值,分别是x,y,w,h;x,y是矩阵左上点的坐标,w,h是矩阵的宽和高。

  • sorted()-key参数-高级排序

key参数的值为一个函数,此函数只有一个参数且返回一个值用来进行比较。

s= [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]
sortedList = sorted(s, key=lambda x: x[2],reverse=True)   # sort by age
print(sortedList)

输出台:

[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

代码复现

  • 版本:opencv-python 4.2.0
# 导入工具包
import cv2
from imutils import contours
import numpy as np
# 构造两个工具函数
# 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
	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

# 用来根据确定宽度或高度,自定义压缩放大图像
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
	dim = None
	(h, w) = image.shape[:2]
	if width is None and height is None:
		return image
	if width is None:
		r = height / float(h)
		dim = (int(w * r), height)
	else:
		r = width / float(w)
		dim = (width, int(h * r))
	resized = cv2.resize(image, dim, interpolation=inter)
	return resized
  • 相关参数以及绘图准备:
# 指定参数
# templateImg 是模板图像
# testImg 是测试图像
# 注意这里的指定路径更换
templateImg = r"E:\mystore\findCard\images\ocr_a_reference.png"
testImg = r"E:\mystore\findCard\images\credit_card_02.png"


# 绘图展示
def cv_show(name, img):
	cv2.imshow(name, img)
	cv2.waitKey(0)
	cv2.destroyAllWindows()
  • 模板图像处理:
# 读取一个模板图像
img = cv2.imread(templateImg)
cv_show('img', img)
# 灰度图
ref = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv_show('ref', ref)
# 二值图像
ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1]
cv_show('ref', ref)

原始模板图像:

GhZj9x.png

二值图像:

Ghe8Cq.png

  • 轮廓处理:
# 计算轮廓
# cv2.findContours()函数接受的参数为二值图,即黑白的(不是灰度图),cv2.RETR_EXTERNAL只检测外轮廓,cv2.CHAIN_APPROX_SIMPLE只保留终点坐标
# 返回的list中每个元素都是图像中的一个轮廓

refCnts, hierarchy = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(img, refCnts, -1, (0, 0, 255), 3) 
cv_show('img', img)
refCnts = sort_contours(refCnts, method="left-to-right")[0]  # 排序,从左到右,从上到下
digits = {}

轮廓图:

GhMEX6.png

  • 数字模板映射:
# 遍历每一个轮廓
for (i, c) in enumerate(refCnts):
	# 计算外接矩形并且resize成合适大小
	(x, y, w, h) = cv2.boundingRect(c)
	roi = ref[y:y + h, x:x + w]
	roi = cv2.resize(roi, (57, 88))

	# 每一个数字对应每一个模板
	digits[i] = roi

待处理图像:

GhMRN4.png

  • 对待识别信用卡图像处理:
# 读取输入图像,预处理
image = cv2.imread(testImg)
cv_show('image', image)
image = resize(image, width=300)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv_show('gray', gray)

灰度图像:

GhQZ2n.png

  • 顶帽操作:
# 初始化卷积核
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

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

处理效果:

GhQoGj.png

  • 梯度处理:
gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0,  # ksize=-1相当于用3*3的
	ksize=-1)

gradX = np.absolute(gradX)
(minVal, maxVal) = (np.min(gradX), np.max(gradX))
gradX = (255 * ((gradX - minVal) / (maxVal - minVal)))
gradX = gradX.astype("uint8")

cv_show('gradX', gradX)

处理效果:

GhQbMq.png

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

# 再来一个闭操作

thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel)  # 再来一个闭操作
cv_show('thresh', thresh)

闭操作:

GhleFe.png

阈值处理:

GhlQyt.png

Ghl8w8.png

  • 轮廓处理:
# 计算轮廓

threshCnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
	cv2.CHAIN_APPROX_SIMPLE)

cnts = threshCnts
cur_img = image.copy()
cv2.drawContours(cur_img, cnts, -1, (0, 0, 255), 3) 
cv_show('img', cur_img)
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])
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)
	# 预处理
	group = cv2.threshold(group, 0, 255,
		cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
	cv_show('group', group)
	# 计算每一组的轮廓
	digitCnts, hierarchy = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL,
		cv2.CHAIN_APPROX_SIMPLE)
	digitCnts = contours.sort_contours(digitCnts,
		method="left-to-right")[0]

处理效果:

GhlI0K.png

  • 模板匹配
	# 计算每一组中的每一个数值
	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)

		# 计算匹配得分
		scores = []

		# 在模板中计算每一个得分
		for (digit, digitROI) in digits.items():
			# 模板匹配
			result = cv2.matchTemplate(roi, digitROI,
				cv2.TM_CCOEFF)
			(_, score, _, _) = cv2.minMaxLoc(result)
			scores.append(score)

		# 得到最合适的数字
		groupOutput.append(str(np.argmax(scores)))

提取出:

GhlLpd.png

进一步:

GhlxnP.png

  • 显现对比:
	# 画出来
	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)

# 打印结果
print("Credit Card #: {}".format("".join(output)))
cv2.imshow("Image", image)
cv2.waitKey(0)

Gh1YB6.png

  • 控制台输出:
Credit Card #: 4020340002345678