在正式进行卡号识别编写程序时,我们首先需要知道我们需要使用到的函数。
我们需要用到图像的二值化处理,轮廓筛选,形态学变化,数字截取与排序。
**二值化处理:**图像的二值化类型分为全局阈值和自适应阈值,这里我们用到的时自适应阈值,全局阈值无法得到我们想要的效果。
adapt=cv2.adaptiveThreshold(src,maxVal,adaptiveMethod,type,blockSize,c)
上面为自定义阈值的模板,第一个参数时图片,阈值的最大值,自适应阈值,处理类型,后面是两个常数。
下面的代码如下:
# -*- coding =utf-8 -*-
# @Time :2022/7/1 8:51
# @Author :CHINA
# @File :卡号识别.py
# @software:PyCharm
import cv2
import numpy as np
card_gray=cv2.imread("F:\\7.1\\card .jpg",cv2.IMREAD_GRAYSCALE)
card_gray4=cv2.resize(card_gray,(2*card_gray.shape[1],2*card_gray.shape[0]))
adapt=cv2.adaptiveThreshold(card_gray4,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY_INV,13,3)
con,hiera=cv2.findContours(adapt,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(con)):
if cv2.contourArea(con[i])<160:
adapt=cv2.drawContours(adapt,con,i,(0,0,0),-1)
ker=np.ones((15,15),dtype=np.uint8)
blackhat=cv2.morphologyEx(adapt,cv2.MORPH_BLACKHAT,ker)
ker=np.ones((3,3),dtype=np.uint8)
opening=cv2.morphologyEx(blackhat,cv2.MORPH_OPEN,ker)
con,hiera=cv2.findContours(opening,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(con)):
x,y,w,h=cv2.boundingRect(con[i])
ratio=float(w)/h
Area=w*h
if Area<1800 or Area>6000:
opening = cv2.drawContours(opening, con, i, (0, 0, 0), -1)
else:
if ratio>0.7 or ratio<0.57:
opening = cv2.drawContours(opening, con, i, (0, 0, 0), -1)
cv2.imshow("adapt4",opening)
ker=np.ones((3,3),dtype=np.uint8)
opening=cv2.morphologyEx(opening,cv2.MORPH_DILATE,ker)
cv2.imshow("adapt5",opening)
model=cv2.imread("F:\\7.1\\model.jpg",cv2.IMREAD_GRAYSCALE)
ret,model=cv2.threshold(model,200,255,cv2.THRESH_BINARY)
cv2.imshow("adapt6",model)
def squence(image,width,height):
con, hiera = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
n=len(con)
Reactbox0=np.ones((n,4),dtype=int)
for i in range(n):
Reactbox0[i]=cv2.boundingRect(con[i])
Reactbox= np.ones((n, 4), dtype=int)
for i in range (n):
p=0
for j in range(n):
if Reactbox0[i][0]>Reactbox0[j][0]:
p=p+1
Reactbox[p]=Reactbox0[i]
Imgbox=[[]for i in range (n)]
for i in range (n):
x,y,w,h=Reactbox[i]
ROI=image[y:y+h,x:x+w]
ROI = cv2.resize(ROI,(width,height))
thresh,ROI=cv2.threshold(ROI,200,255,cv2.THRESH_BINARY)
Imgbox[i]=ROI
return Reactbox,Imgbox
Reactbox_Temp,Imgbox_Temp=squence(model,50,80)
print(Reactbox_Temp)
cv2.imshow("adapt7",Imgbox_Temp[1])
Reactbox,Imgbox=squence(opening,50,80)
for i in range (len(Imgbox)):
score=np.zeros(len(Imgbox_Temp),dtype=int)
for j in range(len(Imgbox_Temp)):
score[j]=cv2.matchTemplate(Imgbox[i],Imgbox_Temp[j],cv2.TM_SQDIFF)
min_val,max_val,min_indx,max_indx=cv2.minMaxLoc(score)
print(min_indx[1])
cv2.waitKey(0)