import cv2
import numpy as n
img = cv2.imread("moban.png", 1)
img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img1 = cv2.threshold(img1, 0, 255, cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)[1]
img1_con = cv2.findContours(img1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0]
img1_dst = cv2.drawContours(img.copy(), img1_con, -1, (0, 0, 255), 2)
cv2.imshow('1', img1_dst)
l = []
for con in img1_con:
(x, y, w, h) = cv2.boundingRect(con)
l.append(x)
(img1_con, l) = zip(*sorted(zip(img1_con, l), key=lambda x: x[1], reverse=False))
dig = {}
for i, con in enumerate(img1_con):
(x, y, w, h) = cv2.boundingRect(con)
roi = img1[y:y + h, x:x + w]
dig[i] = cv2.resize(roi, (57, 88))
card = cv2.imread("yinhangka.jpg", 1)
card1 = cv2.cvtColor(card, cv2.COLOR_BGR2GRAY)
kernel = np.ones((5, 5))
tophat = cv2.morphologyEx(card1, cv2.MORPH_TOPHAT, kernel)
cv2.imshow('2', tophat)
grady = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=3)
grady = cv2.convertScaleAbs(grady)
gradx = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=3)
gradx = cv2.convertScaleAbs(gradx)
grad = cv2.addWeighted(gradx, 0.5, grady, 0.5, 0)
cv2.imshow('3', grad)
kernel = np.ones((3, 3))
grad_close = cv2.morphologyEx(grad, cv2.MORPH_CLOSE, kernel, iterations=1)
cv2.imshow('4', grad_close)
grad_dst = cv2.threshold(grad_close, 0, 255, cv2.THRESH_OTSU)[1]
grad_close = cv2.morphologyEx(grad_dst, cv2.MORPH_CLOSE, kernel, iterations=8)
cv2.imshow('5', grad_close)
gradcon = cv2.findContours(grd_close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0]
dst = cv2.drawContours(card.copy(), gradcon, -1, (0, 0, 255), 2)
cv2.imshow('6', dst)
lunkuo = []
for con in gradcon:
(x, y, w, h) = cv2.boundingRect(con)
ar = w/h
if ar > 2.4 and ar < 3.5:
if w > 155 or w < 85:
continue
lunkuo.append((x, y, w, h)
sort_lunkuo = sorted(lunkuo, key=lambda x: x[0], reverse=False)
img_part = []
for i in sort_lunkuo:
x, y, w, h = i[0], i[1], i[2], i[3]
con = np.array([[[x, y], [x+w, y], [x+w, y+h], [x, y+h]]])
img_part.append(card[y:y+h, x:x+w])
cv2.imshow('7', card[y:y+h, x:x+w])
digital = []
def huode(img):
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img2 = cv2.threshold(img_gray, 0, 255, cv2.THRESH_OTSU)[1]
imgcon = cv2.findContours(img2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0]
new_con = []
for con in imgcon:
(x,y,w,h) = cv2.boundingRect(con)
if h > 35 or w < 15:
continue
new_con.append((x, y, w, h))
sort_con = sorted(new_con, key=lambda x: x[0])
for i in sort_con:
x, y, w, h = i[0], i[1], i[2], i[3]
con = np.array([[[x, y], [x+w, y], [x+w, y+h], [x, y+h]]])
roi = img2[y-1:y+h+1, x-1:x+w+1]
digital.append(cv2.resize(roi, (57, 88)))
for i in img_part:
huode(i)
shuzi = []
for img_dig in digital:
now = []
for (dig1, digroi) in dig.items():
res = cv2.matchTemplate(img_dig, digroi, cv2.TM_CCOEFF_NORMED)
now.append(res.item())
shuzi.append(now.index(max(now)))
now.clear()
cv2.waitKey(0)
print(shuzi)