OpenCV入门实战——信用卡卡号识别

808 阅读4分钟

OpenCV入门实战——信用卡卡号识别

Part1 前言

最近在学习OpenCV相关的知识,跟着B站教学视频尝试实践一个简单的小项目——信用卡卡号识别。

Part2 基本流程思维导图

思维导图图.png

Part3 代码详解

#导入所需库和包
from imutils import contours
import numpy as np
import cv2

#用于图片的展示
def cv_show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

#用于图片的成比例resize
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    (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

信用卡卡号由4乘4共16个0-9的数字组成,可以对其进行模板匹配从而识别出卡面上的数字。模板匹配是一项在一幅图像中寻找与另一幅模板图像最匹配部分的技术

template.png

#首先读取template图片
img = cv2.imread("template.png")

#转换成灰度图
ref = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#转换为二值图像
ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1]

#轮廓检测
#--cv2.RETR_EXTERNAL 检测外轮廓
refCnts, hierarchy = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cv2.findContours()函数共有三个参数,第一个参数是待寻找轮廓的图像,第二个参数是轮廓的检测方法,本文为外轮廓检测,第三个参数为轮廓的近似办法。

cv2.findContours()函数接受的参数为二值图,即黑白的(不是灰度图),所以读取的图像要先转成灰度的,再转成二值图。

cv2.findContours()函数会“原地”修改输入的图像。因此传入的是ref.copy()而不是ref

cv2.findContours()函数返回两个值,refCnts是一个list,存有检测出的所有轮廓,hierarchy保存对应轮廓的属性。

cv2.drawContours(img, refCnts, -1, (0, 0, 255), 3)
cv_show('img', img)

绘制轮廓图,展示如下

轮廓.png

将得到的轮廓进行排序,排序方式为从左到右,从上到下

refCnts = contours.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

其中cv2.boundingRect(img)这个函数可以获得一个图像的最小矩形边框一些信息,它可以返回四个参数,左上角坐标(x,y)和矩形的宽高(w,h)。将感兴趣区域 (ROI)取出并resize后存入字典。

为了进行后续的图像形态学操作,例如腐蚀,膨胀,开运算,闭运算 等等,需要初始化内核。

rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

接下来导入待检测的信用卡卡面图片

image = cv2.imread("01.jfif")

image = resize(image, width = 300)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT,rectKernel)

resize后将其转化为灰度图并进行形态学变换中的顶帽操作,使得图像中的亮部更加突出。

tophat.png

接下来进行梯度图像的计算并归一化,用于显示图像的轮廓

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)))
gradX = gradX.astype("uint8")

为了使得卡号一组一组的显示,对图像进行形态学操作闭操作(先膨胀后腐蚀)。中间进行二值化操作。

gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel)

thresh = cv2.threshold(gradX, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel)

对经过处理后的图像再进行轮廓检测,得到许多轮廓后发绘图现有许多并不符合我们意愿的轮廓,因此下一步进行轮廓的筛选。

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 2.5 < ar < 4.0 and (40 < w < 55) and (10 < h < 20):
        locs.append((x, y, w, h))
# 将符合的轮廓从左到右排序
locs = sorted(locs, key=lambda ix: ix[0])

最后将每一组轮廓中的图像截取下来并判断数字,存入groupoutput中

output = []
# 遍历每一个轮廓中的数字
for (i, (gX, gY, gW, gH)) in enumerate(locs):
    groupOutput = []
    
    #取出灰度图中的部分
    group = gray[gY - 5:gY + gH + 5, gX - 5: gX + gW + 5]
    
    # 预处理
    group = cv2.threshold(group, 0, 255, cv2.THRESH_OTSU)[1]
    
    # 计算每一组轮廓
    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:
        (x, y, w, h) = cv2.boundingRect(c)
        roi = group[y: y + h, x: x + w]
        roi = cv2.resize(roi, (57, 88))
        #scores用于存储match的结果
        scores = []
        for (digit, digitROI) in digits.items():
            result = cv2.matchTemplate(roi, digitROI, cv2.TM_CCOEFF)
            (_, score, _, _) = cv2.minMaxLoc(result)
            scores.append(score)
        # 得到最合适的数字,取出值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)
    
cv_show('image', image)

得到最终的结果

结果.png

小结

识别信用卡卡号虽然是一个简单的图像识别的项目,由于是跟着教程全程走下来所以没遇到什么难点,但是还是有很多细节需要注意的。