信用卡数字识别

信用卡数字识别

import argparse #导包
parser = argparse.ArgumentParser() #创建ArgumentParser对象
parser.add_argument() #通过add_argument()告诉ArgumentParser如何将命令行中的参数转化成所需要的对象
parser.parse_args() #存储和使用通过add_argument()得到的信息,检查命令行的参数,并将参数转化成合理的使用类
args=vars( parser.parse_args())
#1知识点补充
礼帽 = 原始输入-开运算结果
黑帽 = 闭运算-原始输入
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
balckhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4iWkQpvs-1597380254746)(D:\学习\线上监控\笔记\image-20200806192250264.png)]

1…将图像转为灰度图像

2.二值化图像

3.画出轮廓

1.初始化卷积核

2读入输入图像,预处理(将图像转为灰度图像)

3.礼帽操作,突出明亮的区域

4.sobel算法,边缘检测

5.通过闭操作(先膨胀,再腐蚀)将数字连在一起

6.二值操作

7.再做闭操作

8.计算轮廓

9遍历轮廓,根据实际任务,留下符合要求的区域

10.将符合的轮廓从左到右排序

import argparse
import cv2
import numpy as np
import myutils
from imutils import contours
def cv_show(name,image):
    cv2.imshow(name,image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
def sortcounts(recnts):
    i=0
    boundingbox=[cv2.boundingRect(c) for c in recnts]
    cnts,boundingbox=zip(*(sorted(zip(recnts,boundingbox),key=lambda b:b[1][0],reverse=False)))
    return cnts,boundingbox
def resize0(img,width=None,height=None,inter=cv2.INTER_AREA):
    dim=None
    h,w=img.shape[:2]
    if width is None and height is None:
        return img
    if width is None:
        r=height / float(h)
        dim=(int(w * r),height)
    else:
        r=width /float(w)
        dim=(width,int(h*r))
    imge=cv2.resize(img,dim,interpolation=inter)
    return imge

ap=argparse.ArgumentParser()
ap.add_argument('-i','--template',required=True,help='pathh to image')
ap.add_argument('-t','--imag',required=True,help='path to template')
arg=vars(ap.parse_args())
#1.将图像转为灰度图像
img=cv2.imread(arg['template'])
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
thresh=cv2.threshold(gray,10,255,cv2.THRESH_BINARY_INV)[1]
#2.画出轮廓
countors1,h=cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# fg=cv2.drawContours(img,countors,-1,(0,0,255),2)
cnts,boungbox=sortcounts(countors1)
digits={}
for (i,c) in enumerate(cnts):
    (x,y,w,h)=cv2.boundingRect(c)
    roi=thresh[y:y+h,x:x+w]
    roi1=cv2.resize(roi,(57,88))
    digits[i]=roi1
#初始化卷积
rectkenel=cv2.getStructuringElement(cv2.MORPH_RECT,(9,3))
sqkenel=cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
timg=cv2.imread(arg['imag'])
fg=myutils.resize(timg,width=300)
tgray=cv2.cvtColor(fg,cv2.COLOR_BGR2GRAY)
#礼帽操作
tophat=cv2.morphologyEx(tgray,cv2.MORPH_TOPHAT,rectkenel)
tsobel=cv2.Sobel(tophat,ddepth=cv2.CV_32F,dx=1,dy=0,ksize=3)#表示32位浮点数
#归一化
grandx=np.absolute(tsobel)
minVal,maxVal=(np.min(grandx),np.max(grandx))
grandx=(255*((grandx-minVal)/(maxVal-minVal)))
cv_show('grands',grandx)
grandx=grandx.astype('uint8')
grandx=cv2.morphologyEx(grandx,cv2.MORPH_CLOSE,rectkenel)
grandx=cv2.threshold(grandx,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)[1]
#再做一次闭操作
grandx=cv2.morphologyEx(grandx,cv2.MORPH_CLOSE,sqkenel)
countors1,h1=cv2.findContours(grandx.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
locos=[]
for (i,c) in enumerate(countors1):
      x,y,w,h=cv2.boundingRect(c)
      ar = w /float(h)
      if ar>2.5 and ar<4.0:
          if (w > 40 and w < 55) and (h > 10 and h < 20):
               locos.append((x,y,w,h))
locos=sorted(locos,key=lambda k:k[0])

for (i,(gx,gy,gw,gh)) in enumerate(locos):
    groupout=[]
    #根据坐标提取每一个租
    group=tgray[gy-5:gy+gh+5,gx-5:gx+gw+5]
    # cv_show('g',group)
    tthresh=cv2.threshold(group,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)[1]
    cv_show('d',tthresh)
    count,h=cv2.findContours(tthresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    # # dicnt,box=contours.sort_contours(count,method='left-to-right')
    # group = cv2.threshold(group, 0, 255,
    #                       cv2.THRESH_BINARY | 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]
    digitCnts = contours.sort_contours(count, method="left-to-right")[0]
    for i in digitCnts:
        # (x, y, w, h) = cv2.boundingRect(i)
        # roi = tthresh[y:y + h, x:x + w]
        #
        # cv_show('roi', roi      )
        (x,y,w,h)=cv2.boundingRect(i)
        toi=tthresh[y:y+h,x:x+w]
        toi1 = cv2.resize(toi, (57, 88))
        scores=[]
        for (digit,digtroi) in digits.items():
           reult=  cv2.matchTemplate(toi1,digtroi,cv2.TM_CCOEFF)#越大越相关(最大值表示最相关,loc表示相关的位置)
           print(reult)
           (minral,maxral, minloc, macloc)=cv2.minMaxLoc(reult)
           scores.append(maxral)
        groupout.append(str(np.argmax(scores)))
    cv2.putText(fg,"".join(groupout),(gx,gy-15),cv2.FONT_HERSHEY_SIMPLEX,0.65,(0,0,255),2)#左上角坐标
cv_show('aed',fg)

ppend(str(np.argmax(scores)))
cv2.putText(fg,"".join(groupout),(gx,gy-15),cv2.FONT_HERSHEY_SIMPLEX,0.65,(0,0,255),2)#左上角坐标
cv_show(‘aed’,fg)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值