網(wǎng)站交互效果網(wǎng)絡(luò)營(yíng)銷的步驟
目錄
一、項(xiàng)目介紹
二、數(shù)據(jù)材料介紹
1、模板圖片(1張)
2、需要處理的信用卡圖片(5張)?
三、實(shí)現(xiàn)過程
1、導(dǎo)入需要用到的庫(kù)
2、設(shè)置命令行參數(shù)
3、模板圖像中數(shù)字的定位處理
4、信用卡圖像處理
5、模板匹配?
四、總結(jié)
一、項(xiàng)目介紹
項(xiàng)目的主要目標(biāo)是實(shí)現(xiàn)信用卡號(hào)碼和類型的識(shí)別。通過圖像處理技術(shù),從信用卡圖像中提取出卡號(hào),將每個(gè)數(shù)字與模板數(shù)字進(jìn)行比對(duì),從而得出信用卡號(hào)碼。并根據(jù)卡號(hào)的第一位數(shù)字判斷信用卡的類型。
二、數(shù)據(jù)材料介紹
1、模板圖片(1張)
2、需要處理的信用卡圖片(5張)?
?
?
?
?
?
三、實(shí)現(xiàn)過程
1、導(dǎo)入需要用到的庫(kù)
import numpy as np
import argparse
import cv2
import myutils
其中myutils模塊為自己編寫的工具模塊,里面包含了對(duì)輪廓進(jìn)行排序的函數(shù)以及自動(dòng)變換圖片大小的函數(shù),內(nèi)容如下:
"""myutil.py"""import cv2# 排序函數(shù)
def sort_contours(cnts, method='left-to-right'):# 初始化排序方向和索引reverse = Falseaxis_index = 0 # 默認(rèn)按 x 軸排序(從左到右或從右到左)# 根據(jù)排序方法設(shè)置排序方向和索引if method == 'right-to-left' or method == 'bottom-to-top':reverse = True # 反向排序if method == 'top-to-bottom' or method == 'bottom-to-top':axis_index = 1 # 按 y 軸排序(從上到下或從下到上)# 計(jì)算每個(gè)輪廓的邊界框bounding_boxes = [cv2.boundingRect(c) for c in cnts]# 將輪廓和邊界框組合在一起combined = list(zip(cnts, bounding_boxes))# 根據(jù)邊界框的坐標(biāo)進(jìn)行排序sorted_combined = sorted(combined, key=lambda x: x[1][axis_index], reverse=reverse)# 解包排序后的輪廓和邊界框sorted_cnts = [item[0] for item in sorted_combined]sorted_bounding_boxes = [item[1] for item in sorted_combined]return sorted_cnts, sorted_bounding_boxes# 變換圖片大小的函數(shù)
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):dim = None(h, w) = image.shape[:2]if width is None and height is None:return imageif 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)#參數(shù)interpolation指定了在圖像大小調(diào)整過程中如何處理像素插值的方法。cv2.INTER_AREA具體意味著使用面積插值方法。return resized
?
2、設(shè)置命令行參數(shù)
- --image為信用卡圖片
- --template為模板圖片
ap = argparse.ArgumentParser()
ap.add_argument('-i','--image',required=True,help='')
ap.add_argument('-t','--template',required=True,help='')
args = vars(ap.parse_args())# 信用卡號(hào)碼開頭對(duì)應(yīng)信用卡的類型
FIRST_NUMBER = {"3":"American Express","4":"Visa","5":"MasterCard","6":"Discover Card"}
# 定義顯示圖片函數(shù)
def cv_show(name, image):cv2.imshow(name, image)cv2.waitKey(0)
3、模板圖像中數(shù)字的定位處理
-
讀取模板圖像(包含 0-9 的數(shù)字)。
-
對(duì)模板圖像進(jìn)行灰度化、二值化處理。
-
使用輪廓檢測(cè)提取每個(gè)數(shù)字的輪廓,并將每個(gè)數(shù)字裁剪出來(lái),保存為模板。
"""模板圖像中數(shù)字的定位處理"""
# img為模板圖像
img = cv2.imread(args['template'])
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)
# 輪廓
refCnts = cv2.findContours(ref.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[1]
cv2.drawContours(img,refCnts,-1,(0,0,255),2)
cv_show('img',img)
# 對(duì)輪廓進(jìn)行從左到右排序
refCnts = myutils.sort_contours(refCnts,method="left-to-right")[0]
digits = {}
# 獲取每個(gè)數(shù)字的信息
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] = roicv_show('roi',roi)
print(len(digits))
?
4、信用卡圖像處理
-
讀取信用卡圖像。
-
對(duì)信用卡圖像進(jìn)行灰度化、頂帽操作(去除背景)、閉操作(將數(shù)字連在一起)、自適應(yīng)二值化等處理。
-
使用輪廓檢測(cè)找到信用卡上的數(shù)字區(qū)域。
"""信用卡的圖像處理"""
image = cv2.imread(args['image'])
cv_show('image',image)
# 變換圖片大小
image = myutils.resize(image,width=300)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv_show('gray',gray)
# 設(shè)置核
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT,(9,3))
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
# 頂帽
tophat = cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,rectKernel)
# 開運(yùn)算
open = cv2.morphologyEx(gray,cv2.MORPH_OPEN,rectKernel)
cv_show('open',open)
cv_show('tophat',tophat)# 找數(shù)字邊框
# 閉操作,將數(shù)字連在一起
closeX = cv2.morphologyEx(tophat,cv2.MORPH_CLOSE,rectKernel)
cv_show('closeX',closeX)# 自適應(yīng)二值化
thresh = cv2.threshold(closeX,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
cv_show('thresh',thresh)# 閉操作
thresh = cv2.morphologyEx(thresh,cv2.MORPH_CLOSE,sqKernel)
cv_show('thresh1',thresh)# 計(jì)算輪廓
threshCnts = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[1]
cnts = threshCnts
cur_img = image.copy()
cv2.drawContours(cur_img,cnts,-1,(0,0,255),3)
cv_show('img',cur_img)# 遍歷輪廓,找到數(shù)字部分
locs = [] # 存放每組數(shù)字的x,y,w,h
for (i,c) in enumerate(cnts):(x,y,w,h) = cv2.boundingRect(c)ar = w/float(h)if 2.5 < ar < 4.0:if (40 < w < 55) and (10 < h < 20):locs.append((x,y,w,h))
locs = sorted(locs,key=lambda x: x[0])
?
?
5、模板匹配?
-
將信用卡圖像中的每個(gè)數(shù)字區(qū)域與模板中的數(shù)字進(jìn)行匹配,找到最相似的數(shù)字。
-
根據(jù)匹配結(jié)果識(shí)別信用卡號(hào)碼。
output = []
# 遍歷每一組數(shù)字
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_BINARY | cv2.THRESH_OTSU)[1]cv_show("group",group)# 尋找每組數(shù)字的輪廓并根據(jù)順序放入digitCntsdigitCnts = cv2.findContours(group.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[1]digitCnts = myutils.sort_contours(digitCnts)[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)"""模板匹配,計(jì)算得分"""scores = []# 在模板中計(jì)算每一個(gè)得分for (digit,digitROI) in digits.items():# 模板匹配result = cv2.matchTemplate(roi,digitROI,cv2.TM_CCOEFF)# minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(src, mask=None)score = cv2.minMaxLoc(result)[1]scores.append(score)# 得到匹配分?jǐn)?shù)最大值的索引groupOutput.append(str(np.argmax(scores)))cv2.rectangle(image,(gx-5,gy-5),(gx+gw+5,gy+gh+5),(0,0,255),1)cv2.putText(image,"".join(groupOutput),(gx,gy-15),cv2.FONT_HERSHEY_SIMPLEX,0.65,(0,255,0),2)output.extend(groupOutput)# 打印結(jié)果
print("信用卡類型:{}".format(FIRST_NUMBER[output[0]]))
print("信用卡號(hào)碼:{}".format("".join(output)))
cv_show("Image",image)
?
?
?
四、總結(jié)
這個(gè)項(xiàng)目通過圖像處理和模板匹配技術(shù),實(shí)現(xiàn)了信用卡號(hào)碼的自動(dòng)識(shí)別。它展示了如何結(jié)合 OpenCV 和 Python 實(shí)現(xiàn)一個(gè)實(shí)用的圖像處理應(yīng)用。
?