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

1 整体思路

  1. 数字模板图像处理:先将数字模板图像中的10个数字分别用矩形包围框(对应boundingRect函数)给包起来,然后对轮廓排序,之后将每个矩形框的大小调整为宽57高88大小,最后用一个字典将所有的数字模板存储起来,这个字典的key为数字模板对应的数字,value为数字模板。
  2. 信用卡图像处理:通过礼帽、Sobel梯度、闭操作、阈值处理等操作将文字区域显示出来,然后通过调用findContours找出所有的轮廓,接着依次遍历每个轮廓,留下长宽比在2.54.0之间且宽度在4055之间高度在10~20之间的轮廓。
  3. 信用卡数字匹配:遍历每个保留下来的数字整体轮廓位置,对每个数字整体轮廓再使用矩形包围框(对应boundingRect函数)给包起来,假设其为roi,然后将每个矩形框roi的大小调整为宽57高88大小,之后使用模板匹配的方法,将每个roi与数字模板图像进行比对,得分最高的数字模板对应的key即为roi对应的数字。
  4. 展示匹配结果:将roi对应的数字收集起来,就可以得到信用卡对应的数字。

2 相关包和工具函数

import cv2
from matplotlib import pyplot as plt
from imutils import contours
import numpy as np

def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    """
    调整图像大小并保持纵横比。

    :param image: 要调整大小的原始图像。
    :param width: 新图像的宽度。如果未指定,则根据高度自动计算。
    :param height: 新图像的高度。如果未指定,则根据宽度自动计算。
    :param inter: 插值方法,默认为cv2.INTER_AREA,适用于图像缩小。
    :return: 调整大小后的图像。
    """
    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

def cv_show(name, image):
    """
    使用Matplotlib显示图像。

    :param name: 图像的标题。
    :param image: 要显示的图像。假设图像是OpenCV的BGR格式。
    """
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    fig, ax = plt.subplots()
    ax.set_xticks([])  # 移除x轴刻度
    ax.set_yticks([])  # 移除y轴刻度
    plt.title(name)   # 设置图像标题
    plt.imshow(image_rgb)  # 显示RGB格式的图像
    plt.show()

3 数字模板处理

img = cv2.imread('./images/ocr_a_reference.png')
cv_show('img',img)

image-20240126110911014

# 灰度图
ref = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv_show('ref',ref)

image-20240126111007767

ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1]
cv_show('ref',ref)

image-20240126111045307

# 计算轮廓
#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)
print("轮廓数为:"+len(refCnts))

image-20240126111326304

轮廓数为:10

refCnts = contours.sort_contours(refCnts, method="left-to-right")[0] #排序,从左到右,从上到下
digits = {}
rows = 2
cols = 5
fig, axs = plt.subplots(rows, cols, figsize=(16, 8))
# 遍历每一个轮廓
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))
	row = i // cols
	col = i % cols

    # 显示子图
	axs[row, col].imshow(roi, cmap='gray')
	axs[row, col].set_title(str(i), fontsize=28)  # 设置标题为轮廓序号
	axs[row, col].axis('off')  # 关闭坐标轴
	# 每一个数字对应每一个模板
	digits[i] = roi
plt.tight_layout()
plt.show()

image-20240126143630875

4 信用卡处理

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

#读取输入图像,预处理
image = cv2.imread('./images/credit_card_01.png')
cv_show('image',image)
image-20240126111533533
image = resize(image, width=300)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv_show('gray',gray)
image-20240126111624473
#礼帽操作,突出更明亮的区域
tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel) 
cv_show('tophat',tophat) 
image-20240126143734284
Sobelx = cv2.Sobel(tophat, cv2.CV_64F,1,0)
Sobely = cv2.Sobel(tophat, cv2.CV_64F,0,1)
Sobelx = cv2.convertScaleAbs(Sobelx)
Sobely = cv2.convertScaleAbs(Sobely)
Sobelxy =  cv2.addWeighted(Sobelx,0.5, Sobely,0.5,0)
cv_show('Sobelxy',Sobelxy)
image-20240126143808921
#通过闭操作(先膨胀,再腐蚀)将数字连在一起
gradX = cv2.morphologyEx(Sobelxy, cv2.MORPH_CLOSE, rectKernel) 
cv_show('gradX',gradX)
image-20240126143858360
#THRESH_OTSU会自动寻找合适的阈值,适合双峰,需把阈值参数设置为0
thresh = cv2.threshold(gradX, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] 
cv_show('thresh',thresh)
image-20240126143940635
#再来一个闭操作

thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel) #再来一个闭操作
cv_show('thresh',thresh)
image-20240126144018051
# 计算轮廓

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)
image-20240126144103784

5 信用卡数字匹配

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]

	# 计算每一组中的每一个数值
	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)
		print(scores)
		print("最大分数的索引为:"+ str(np.argmax(scores)))
		# 得到最合适的数字
		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)
image-20240126150615587 image-20240126150644677 image-20240126150726901
[-4182007.25, -17584746.0, -7006532.5, -5838328.0, 48703036.0, -14565888.0, 14520973.0, -5111222.5, -1669509.75, -1378032.125]
最大分数的索引为:4
image-20240126150811984
[60324688.0, 255238.34375, 33025072.0, 30227486.0, 13670484.0, 12007651.0, 34056056.0, 8450211.0, 9934947.0, 30924364.0]
最大分数的索引为:0
image-20240126150903091
[64481688.0, 3487170.5, 34764428.0, 32162430.0, 10000470.0, 13646384.0, 35208812.0, 7919825.5, 13613242.0, 31187082.0]
最大分数的索引为:0
image-20240126150951921
[60497356.0, 1452328.125, 34448520.0, 31327738.0, 12722555.0, 11564593.0, 35273016.0, 7656688.5, 10062867.0, 29857338.0]
最大分数的索引为:0

6 展示匹配结果

print("Credit Card Type: American Express")
print("Credit Card #: {}".format("".join(output)))
cv_show("Image", image)

image-20240126151105294

Credit Card Type: American Express
Credit Card #: 4000123456789010
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
from imutils import contours import numpy as np import argparse import cv2 as cv import myutils def cv_show(name,img): cv.imshow(name,img) cv.waitKey(0) cv.destroyAllWindows() # 先处理template tempalte_img = cv.imread("E:/opencv/picture/ocr_a_reference.png") tempalte_gray = cv.cvtColor(tempalte_img, cv.COLOR_BGR2GRAY) tempalte_thres = cv.threshold(tempalte_gray, 0, 255, cv.THRESH_OTSU | cv.THRESH_BINARY_INV)[1] temp_a, tempalte_contours, temp_b = cv.findContours(tempalte_thres.copy (), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) cv.drawContours(tempalte_img, tempalte_contours, -1, (0, 255, 0), 2) tempalte_contours = contours.sort_contours(tempalte_contours, method="left-to-right")[0] digits = {} # 构建一个字典 for (i, c) in enumerate(tempalte_contours): (x, y, w, h) = cv.boundingRect(c) tempalte_roi = tempalte_thres[y:y + h, x:x + w] #之前一直检测不出正确答案,原因是这里的roi应该是tempalte_thres一部分 #而不是template_gray的一部分! tempalte_roi = cv.resize(tempalte_roi, (57, 88)) digits[i] = tempalte_roi cv_show('template_single',tempalte_roi) #cv_show('template_single',tempalte_roi) #对银行卡进行处理,之所以要做成数字长条,是想通过长条的尺寸比例大小来将自己想要的数字给抠出来。 rectkernel = cv.getStructuringElement(cv.MORPH_RECT,(9,3)) squrkernel = cv.getStructuringElement(cv.MORPH_RECT,(5,5)) image = cv.imread("E:/opencv/picture/credit_card_02.png") image = myutils.resize(image, width=300) image_gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY) image_tophat= cv.morphologyEx(image_gray,cv.MORPH_TOPHAT,rectkernel) image_close = cv.morphologyEx(image_tophat,cv.MORPH_CLOSE,rectkernel) cv.imshow("image_tophat",image_tophat) cv.imshow('image_close',image_close) image_thres= cv.threshold(image_close,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)[1] image_contours= cv.findContours(image_thres.copy(),cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)[1] locs = [] for(n,con) in enumerate(image_contours): (gx,

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值