import cv2
global method =
img = cv2.imread(img_path)
template = cv2.imread(img_path)
def cv_show(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def get_match_rec(template, img, method):
# 计算出模板宽高
th, tw = template.shape[:2]
res = cv2.matchTemplate(img, template, method)
# 找出最大值
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0]+tw, top_left[1] + th)
return top_left, bottom_right
template = cv2.imread(template_path)
img = cv2.imread(img_path)
top_left, bottom_right = get_match_rec(img, template, method=cv2.TM_CCOEFF)
print(top_left)
cv2.rectangle(img, top_left, bottom_right, (0, 255, 0), 2)
# 裁剪匹配区域
crop_img = img[top_left[1]:(top_left[1]+ template.shape[0]),
top_left[0]:(top_left[0] + template.shape[1])]
cv_show('template',crop_img)
674





