1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| import cv2 import numpy as np def templateInit(): img = cv2.imread("template.png") img = cv2.GaussianBlur(img,(3,3),1) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) _,binary = cv2.threshold(gray,128,255,cv2.THRESH_BINARY_INV) _,contour,_ = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(binary,contour,-1,(0,0,255),2) boundingBoxes = [cv2.boundingRect(c) for c in contour] contour,_ = zip(*sorted(zip(contour, boundingBoxes),key=lambda b: b[1][0], reverse=False)) list = [] for (i) in contour: (x,y,w,h)= cv2.boundingRect(i) cv2.rectangle(img,(x,y),(w+x,h+y),(0,0,255),1) ROI = binary[y:y + h, x:x + w] ROI=cv2.resize(ROI.copy(),(57,88)) list.append(ROI)
return binary,contour,list
binary,templateContours,list = templateInit() creditCard = cv2.imread("CreditCard.png") img = cv2.GaussianBlur(creditCard, (3, 3), 1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_,creditBinay = cv2.threshold(gray.copy(),128,255,cv2.THRESH_BINARY_INV) _, creditContour, _ = cv2.findContours(creditBinay, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(creditBinay, creditContour, -1, (0, 0, 255), 2)
boundingBoxes = [cv2.boundingRect(c) for c in creditContour] creditContour, _ = zip(*sorted(zip(creditContour, boundingBoxes), key=lambda b: b[1][0], reverse=False))
numList=[] filtedContour=[] for i in creditContour: (x, y, w, h) = cv2.boundingRect(i) if (0.58 < w / h < 0.70) and (31<x<422) and (145<y<201): filtedContour.append(i) cv2.drawContours(creditCard,filtedContour,-1,(0,0,255),2) for i in filtedContour: (x, y, w, h) = cv2.boundingRect(i) cv2.rectangle(img, (x, y), (w + x, h + y), (0, 0, 255), 1) ROI = gray[y:y + h, x:x + w] _,ROI = cv2.threshold(ROI.copy(),128,255,cv2.THRESH_BINARY) ROI = cv2.resize(ROI.copy(), (57, 88)) maxList = [] for templateROI in list: result = cv2.matchTemplate(ROI,templateROI,cv2.TM_CCOEFF) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) maxList.append(max_val) maxValue = 0 Index = 0 for i in range(10): if maxList[i] > maxValue: maxValue = maxList[i] Index = i if not (maxValue == 0): cv2.putText(creditCard,str(Index),(x,y-10),1,1,(0,0,255))
numList.append(Index)
cv2.imshow("asd",creditCard) cv2.waitKey(0) print(numList)
|