OpenCV信用卡数字识别

本文介绍了如何利用OpenCV进行信用卡数字识别。首先引入必要的库,然后读取和处理数据,通过阈值处理、轮廓检测等步骤筛选出信用卡号码。通过对数字模板的匹配,成功识别出信用卡上的每个数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

案例来源于© Fu Xianjun. All Rights Reserved.

活运用阈值处理、轮廓检测、边缘检测及模板匹配

1.引入库

代码如下(示例):

1.对模板图片进行处理,得到每个数字的模板。

import cv2
import numpy as np
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(cnt) for cnt in cnts]#获得轮廓坐标
    (cnts,boundingBoxes) = zip(*sorted(zip(cnts,boundingBoxes),\
                                      key=lambda b: b[1][i],\
                                       reverse=reverse))
    #打包,并创建一个b的函数
    return cnts, boundingBoxes

2.读入数据

代码如下(示例):

读图及预处理:

def cv_show(name,img):#定义函数,显示图片
    cv2.imshow(name,img)
    cv2.waitKey()
    cv2.destroyAllWindows()
    
template = cv2.imread("ocr_a_reference.png")#读取模板图片
# cv_show("template",template)#显示模板
template_gray = cv2.cvtColor(template,cv2.COLOR_BGR2GRAY)#转换为灰度图
# cv_show("template_gray",template_gray)
ret,template_binary = cv2.threshold(template_gray,127,255,1)\
#二值化,阈值处理
cv_show("template_binary",template_binary)

这里threshold后面的[1]表示取threshold函数返回值的第二个。threshold函数返回值为阈值和二值化后的图片,即这里仅保存返回后的图片。
在这里插入图片描述

该处使用的url网络请求的数据。


cnts,he = cv2.findContours(template_binary,cv2.RETR_EXTERNAL,\
                          cv2.CHAIN_APPROX_SIMPLE)
#查找轮廓
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值