其他分享
首页 > 其他分享> > OPEN CV系列五:实战银行卡号识别

OPEN CV系列五:实战银行卡号识别

作者:互联网

ocr_template_match.py

 

import numpy as np
import argparse
import myutils
import cv2

# 设置参数
# 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': 'Viso',
'5': 'MasterCard',
'6': 'Discover Card'
}

# 图像显示
def cv_show(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 读取模图案
img = cv2.imread('00.png')
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)
# 计算轮廓 cv2.RETR_EXTERNAL只检测外轮廓 cv2.CHAIN_APPROX_SIMPLE 只保留终点坐标点
ref_, refCnts, hierachy = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, refCnts, -1, (0, 255, 255), 3)
cv_show('img', img)
print(np.array(refCnts).shape) # 轮廓的个数
refCnts = myutils.sort_contours(refCnts, method='left-to-right')[0] # 排序从左到右 从上到下
digits = {}

# 遍历每一个轮廓
for (i, c) in enumerate(refCnts):
(x, y, w, h) = cv2.boundingRect(c)
roi = ref[y:y+h, x:x+w]
roi = cv2.resize(roi, (57, 88))
# 每一个数字对应一个模板
digits[i] = roi

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

# 读取银行卡图片
image = cv2.imread('01.png')
cv_show('image', image)
image = cv2.resize(image, (300, 194))
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv_show('gray', gray)

# 礼帽操作 突出更明显的区域 去掉背景那些噪音点
tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel)
cv_show('tophat', tophat)

# 梯度 做边缘检测
gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1) # ksize=-1表示相当于3*3的卷积核
gradX = np.absolute(gradX) # 绝对值
(minVal, maxVal) = (np.min(gradX), np.max(gradX))
gradX = (255 * ((gradX - minVal) / (maxVal - minVal))) # 归一化
gradX = gradX.astype('uint8')
print(np.array(gradX).shape)
cv_show('gradX', gradX)

gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel) # 闭操作
cv_show('gradX', gradX)
thresh = cv2.threshold(gradX, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] # cv2.THRESH_OTSU会自动寻找合适的阈值,适合双峰, 需把与之阈值参数设置为0
cv_show('thresh', thresh)
# 再来一个闭操作
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel)
cv_show('thresh', thresh)

# 计算轮廓
thresh_, threshCnts, hierachy = 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):

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)

# 计算每一组的其中四个数字的轮廓
group_, digitCnts, hierachy = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
digitCnts = myutils.sort_contours(digitCnts, method='left-to-right')[0]

i = 0
# 计算轮廓中的每一个数值
for c in digitCnts:
# 找到当前每一个数的轮廓,reszie为合适的大小
(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)))
print(groupOutput)

# 画出框
cv2.rectangle(image, (gX - 5, gY - 5), (gX + gW +5, gY + gH +5), (0, 0, 255), 1)
cv2.putText(image, str(groupOutput[-1]), (gX + i * 13, gY - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 255), 2)
i += 1
# 得到结果
output.extend(groupOutput)

# 打印结果
cv_show('image', image)

myutils.py
import cv2
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
boundingxBoxes = [cv2.boundingRect(c) for c in cnts] # 外接矩形
(cnts, boundingxBoxes) = zip(*sorted(zip(cnts, boundingxBoxes), key=lambda b: b[1][i], reverse=reverse)) # 排序操作
return cnts, boundingxBoxes
模板图:

银行卡图:

识别结果图:





标签:img,show,银行卡,image,cv2,cv,gradX,OPEN,CV
来源: https://www.cnblogs.com/yuganwj/p/13837081.html