import cv2
kele = cv2.imread('kele.png')
template = cv2.imread('template.png')
cv2.imshow('kele', kele)
cv2.imshow('template', template)
h, w = template.shape[:2]
res = cv2.matchTemplate(kele, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
kele_template = cv2.rectangle(kele, top_left, bottom_right, (0,255,0), 2)
cv2.imshow('Kele_template', kele_template)
cv2.waitKey(0)
cv2.destroyAllWindows()
import numpy as np
import argparse
import cv2
def sort_contours(contours, method="left-to-right"):
reverse = False
i = 0
if method == "right-to-left" or method == "bottom-to-top":
reverse = True
if method == "top-to-bottom" or method == "bottom-to-top":
i = 1
boundingBoxes = [cv2.boundingRect(c) for c in contours]
(contours, boundingBoxes) = zip(*sorted(zip(contours, boundingBoxes),
key=lambda x: x[1][i], reverse=reverse))
return (contours, boundingBoxes)
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 image
if 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)
return resized
def cv_show(name, img):
cv2.imshow(name, img)
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="银行卡图像路径")
ap.add_argument("-t", "--template", required=True, help="数字模板图像路径")
args = vars(ap.parse_args())
FIRST_NUMBER = {
"3": "American Express",
"4": "Visa",
"5": "MasterCard",
"6": "Discover Card",
"9": "JCB/UnionPay/Other"
}
ref = cv2.imread(args["template"])
ref_gray = cv2.cvtColor(ref, cv2.COLOR_BGR2GRAY)
ref_thresh = cv2.threshold(ref_gray, 10, 255, cv2.THRESH_BINARY_INV)[1]
_, refCnts, _ = cv2.findContours(ref_thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
refCnts = sort_contours(refCnts, method="left-to-right")[0]
digits = {}
for (i, c) in enumerate(refCnts):
(x, y, w, h) = cv2.boundingRect(c)
roi = ref_thresh[y:y+h, x:x+w]
roi = cv2.resize(roi, (57, 88))
digits[i] = roi
image = cv2.imread(args["image"])
image = resize(image, width=300)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel)
closeX = cv2.morphologyEx(tophat, cv2.MORPH_CLOSE, rectKernel)
thresh = cv2.threshold(closeX, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel)
_, cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
locs = []
for (i, c) in enumerate(cnts):
(x, y, w, h) = cv2.boundingRect(c)
ar = w / float(h)
if 2.5 < ar < 4.0 and (40 < w < 55) and (10 < 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 = gray[gY - 5:gY + gH + 5, gX - 5:gX + gW + 5]
group_thresh = cv2.threshold(group, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
_, digitCnts, _ = cv2.findContours(group_thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
digitCnts = sort_contours(digitCnts, method="left-to-right")[0]
for c in digitCnts:
(x, y, w, h) = cv2.boundingRect(c)
roi = group_thresh[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)
(_, score, _, _) = cv2.minMaxLoc(result)
scores.append(score)
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, 0, 255), 2)
output.extend(groupOutput)
print(f"银行卡类型:{FIRST_NUMBER[output[0]]}")
print(f"银行卡卡号:{''.join(output)}")
cv2.imshow("识别结果", image)
cv2.waitKey(0)
cv2.destroyAllWindows()