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 91 92 93 94 95 96 97 98
| import cv2 import numpy as np from User.Code import MyTools from User.Code.MyTools import plt_show, cv_show, sort_contours
Template = cv2.imread('./img/Template.png') Template_gray = cv2.cvtColor(Template,cv2.COLOR_BGR2GRAY) Template_bw = cv2.threshold(Template_gray,10,255,cv2.THRESH_BINARY_INV)[1]
binary, contours, hierarchy = cv2.findContours(Template_bw.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours_sorted = sort_contours(contours,method="left-to-right")[0]
digits = {} for (i,c) in enumerate(contours_sorted): (x,y,w,h) = cv2.boundingRect(c) roi = Template_bw[y:y+h,x:x+w] roi = cv2.resize(roi,(57,88)) digits[i] = roi
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT,(9,3)) sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
img = cv2.imread('./img/card3.png') img = MyTools.resize(img,300) img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
tophat = cv2.morphologyEx(img_gray,cv2.MORPH_TOPHAT,rectKernel)
sobelx = cv2.Sobel(tophat,cv2.CV_32F,1,0,ksize = -1) sobelx = np.absolute(sobelx) (minVal,maxVal) = (np.min(sobelx),np.max(sobelx)) sobelx = (255*((sobelx - minVal)/(maxVal - minVal))) sobelx = sobelx.astype("uint8")
sobelx = cv2.morphologyEx(sobelx,cv2.MORPH_CLOSE,rectKernel)
thresh = cv2.threshold(sobelx,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)[1]
thresh = cv2.morphologyEx(thresh,cv2.MORPH_CLOSE,rectKernel)
binary_thresh, contours_thresh, hierarchy_thresh = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
locs = [] for (i,c) in enumerate(contours_thresh): (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): locs.append((x,y,w,h))
locs = sorted(locs,key=lambda x:x[0])
output = []
for (i,(gX,gY,gW,gH)) in enumerate(locs): groupOutput = [] group = img_gray[gY-5:gY+gH+5,gX-5:gX+gW+5] group = cv2.threshold(group, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] binary_group, contours_group, hierarchy_group = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) contours_group = sort_contours(contours_group,method="left-to-right")[0]
for c in contours_group: (x,y,w,h) = cv2.boundingRect(c) roi = group[y:y + h, x:x + w] roi = cv2.resize(roi, (57, 88)) scores = [] for (digit,digitROI) in digits.items(): result = cv2.matchTemplate(roi,digitROI,cv2.TM_CCOEFF) (min_val, max_val, min_loc, max_loc) = cv2.minMaxLoc(result) score = max_val scores.append(score) groupOutput.append(str(np.argmax(scores))) output.extend(groupOutput) result = "".join(output) print(result)
|