基于python和opencv实现信用卡数字识别
本项目和源码来源于唐宇迪opencv项目实战
1.准备工作
- python3.5
- opencv4.2
- 同一字体,相似类型的信用卡图片
- 字体模板图片
![信用卡图片](https://i-blog.csdnimg.cn/blog_migrate/d4a26e0189ff10cdb695ff3e7f3c47cd.png)
![字体模板图片](https://i-blog.csdnimg.cn/blog_migrate/fa87590a7642ff85354370c7307de2c6.png)
2.本项目总体可分为两部分:
3.应用到的数字图像处理基础知识
- 图像灰度处理
- 图像二值化处理
- 检测轮廓,画出轮廓
- 画图形的外接矩形
- 图像的形态学操作
4.先放代码, 我把每一步生成的图片都显示出来,以便观察每一步操作所起的作用
from imutils import contours
import numpy as np
import argparse
import cv2
import myutils
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": "Visa",
"5": "MasterCard",
"6": "Discover Card"
}
template = cv2.imread(args["template"])
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
template_thresh = cv2.threshold(template_gray, 10, 255, cv2.THRESH_BINARY_INV)[1]
refCnts, hierarchy = cv2.findContours(template_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
template_c = template.copy()
template_draw = cv2.drawContours(template_c, refCnts, -1, (255, 170, 0), 3)
print('refCnts', 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 = template_thresh[y:y + h, x:x + w]
roi = cv2.resize(roi, (57, 88))
digits[i] = roi
cv2.imshow("roi", roi)
cv2.waitKey(100)
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
image = cv2.imread(args["image"])
image_resize = myutils