Python开发之基于模板匹配的信用卡数字识别功能
作者:虐猫人薛定谔i 发布时间:2021-08-09 22:30:27
标签:模板,匹配,数字,识别
目录
环境介绍
原理介绍
环境介绍
Python 3.6 + OpenCV 3.4.1.15
原理介绍
首先,提取出模板中每一个数字的轮廓,再对信用卡图像进行处理,提取其中的数字部分,将该部分数字与模板进行匹配,即可得到结果。
模板展示
完整代码
# !/usr/bin/env python
# —*— coding: utf-8 —*—
# @Time: 2020/1/11 14:57
# @Author: Martin
# @File: utils.py
# @Software:PyCharm
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
boundingboxes = [cv2.boundingRect(c) for c in cnts]
(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):
(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
# !/usr/bin/env python
# —*— coding: utf-8 —*—
# @Time: 2020/1/11 14:57
# @Author: Martin
# @File: template_match.py
# @Software:PyCharm
"""
基于模板匹配的信用卡数字识别
"""
import cv2
import utils
import numpy as np
# 指定信用卡类型
FIRST_NUMBER = {
'3' : 'American Express',
'4' : 'Visa',
'5' : 'MasterCard',
'6' : 'Discover Card'
}
# 绘图显示
def cv_show(name, image):
cv2.imshow(name, image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 读取模板图像
img = cv2.imread('./images/ocr_a_reference.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)
# 计算轮廓
ref_, 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(np.array(refCnts).shape)
# 排序,从左到右,从上到下
refCnts = utils.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))
# 读取输入图像,预处理
img_path = input("Input the path and image name: ")
image_input = cv2.imread(img_path)
cv_show('image', image_input)
image_input = utils.resize(image_input, width=300)
gray = cv2.cvtColor(image_input, 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)
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]
cv_show('thresh', thresh)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel)
cv_show('thresh', thresh)
# 计算轮廓
thresh_, threshCnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = threshCnts
cur_img = image_input.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])
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_OTSU)[1]
cv_show('group', group)
# 计算每一组轮廓
group_, digitCnts, hierarchy = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
digitCnts = utils.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))
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)))
cv2.rectangle(image_input, (gX - 5, gY - 5), (gX + gW + 5, gY + gH + 5), (0, 0, 255), 1)
cv2.putText(image_input, "".join(groupOutput), (gX, gY - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 255), 2)
# 得到结果
output.extend(groupOutput)
# 打印结果
print("Credit Card Type: {}".format(FIRST_NUMBER[output[0]]))
print("Credit Card #: {}".format("".join(output)))
cv2.imshow("Image", image_input)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果展示
Credit Card Type: Visa
Credit Card #: 4020340002345678
总结
以上所述是小编给大家介绍的Python开发之基于模板匹配的信用卡数字识别功能网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
来源:https://blog.csdn.net/Deep___Learning/article/details/103938052
0
投稿
猜你喜欢
- 如下所示:# -*- coding:utf-8 -*-import sysimport osfrom glob import globimp
- 相信很多朋友在用Python写完代码之后都迫不及待的想发给对象交流(装X),但是发源码又要求对方有对应的解释器,一般是行不通的,所以我们要把
- 有关pygal的安装,大家可以参阅《pip和pygal的安装实例教程》。直方图:直方图是一个特殊的条,它可以取3个数值:纵坐标高度,横坐标开
- 概述Python是个非常受欢迎的编程语言,随着近些年机器学习、云计算等技术的发展,Python的职位需求越来越高。下面我收集了10个Pyth
- 用户体验已经是一个老生常谈的话题了。我非常赞同某位达人所说的,用户体验设计应该贯穿于产品从萌芽到出生的整个过程,产品原型、视觉设计、前端开发
- 最近对微格式进行了一些学习,在学习过程中收获不少。在此分享下,欢迎交流!微型格式的优点:1,语义化的HTML和CSS类名称来标记共同内容。2
- 1.自定义线程池import threadingimport Queueimport timequeue = Queue.Queue()de
- 注意:安装opencv之前需要先安装numpy,matplotlib等一、安装方法方法一、在线安装1.先安装opencv-pythonpip
- 随着网络的发展,网速和机器速度的提高,越来越多的网站用到了丰富客户端技术。而现在Ajax则是最为流行的一种方式。JavaScript是一种解
- 记得以前的Windows任务定时是可以正常使用的,今天试了下,发现不能正常使用了,任务计划总是挂起。接下来记录下Python爬虫定时任务的几
- 将转储设备加入到SQL Server备份数据库的地方。在SEM中转储设备是可见性的,并且在设备上的信息被存储在主要数据库的sysdevice
- 上线 Django 项目记录,超简单,避免无意义的踩坑!第一步:安装python管理器在宝塔在线面板安装“ python项目管理器 ”第二步
- 直接进入主题立方体每列颜色不同:# Import librariesimport matplotlib.pyplot as pltfrom
- 对于Python开发用户来讲,PIP安装软件包是家常便饭。但国外的源下载速度实在太慢,浪费时间。而且经常出现下载后安装出错问题。所以把PIP
- 前几天翻出以前写的一个纯CSS仿微软经典菜单,现在看来才感叹,微软的经典菜单确实很经典,至少看起来不觉得厌烦。感叹归感叹,想想既然可以实现下
- 下面一段代码给大家介绍python 脚本生成随机 字母 + 数字密码功能,具体代码如下所述:#coding:utf-8import rand
- 以下实例为通过用户输入两个数字,并计算两个数字之和:# -*- coding: UTF-8 -*-# Filename : test.py#
- 前言昨天把自己的VASP文件处理库进行了打包并上传到PyPI,现在可以直接通过pip和easy_install来安装VASPy啦(同时欢迎使
- Cookie简介首先,我们对Cookie做一个简单的介绍,说明如何利用ASP来维护cookie。Cookie是存储在客户端计算机中的一个小文
- 关于中大型开发b/s开发中的缓存(cache),我的一些看法,有不正确的或者是有笔误的地方,请指正。thanks首先,应该了解基本的,对于缓