当前位置 主页 > 服务器问题 > Linux/apache问题 >
本项目利用python以及opencv实现信用卡的数字识别
前期准备
模板图像处理
读取模板图像 cv2.imread(img) 灰度化处理 cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 二值化 cv2.threshold() 轮廓 - 轮廓信用卡图像处理
读取信用卡图像 cv2.imread(img) 灰度化处理 cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 礼帽处理 cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,rectKernel) Sobel边缘检测 cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1) 闭操作 cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel) 计算轮廓 cv2.findContours 模板检测 cv2.matchTemplate(roi, digitROI,cv2.TM_CCOEFF)原始数据展示
结果展示
1 前期准备
# 导入工具包 # opencv读取图片的格式为b g r # matplotlib图片的格式为 r g b import numpy as np import cv2 from imutils import contours import matplotlib.pyplot as plt %matplotlib inline
# 信用卡的位置 predict_card = "images/credit_card_01.png" # 模板的位置 template = "images/ocr_a_reference.png"
# 指定信用卡类型 FIRST_NUMBER = { "3": "American Express", "4": "Visa", "5": "MasterCard", "6": "Discover Card" }
# 定义一些功能函数 # 对框进行排序 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 # 定义cv2展示函数 def cv_show(name,img): cv2.imshow(name,img) cv2.waitKey(0) cv2.destroyAllWindows()
2 对模板图像进行预处理操作
读取模板图像
# 读取模板图像 img = cv2.imread(template) cv_show("img",img) plt.imshow(img)