-
Notifications
You must be signed in to change notification settings - Fork 0
/
template_matching.py
34 lines (27 loc) · 1.04 KB
/
template_matching.py
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
import cv2
import numpy as np
img_path = 'img/navi_img.png'
template_path = 'img/navi_temp1.png'
img = cv2.imread(img_path)
template = cv2.imread(template_path)
th, tw = template.shape[:2]
cv2.imshow('template', template)
methods = ['cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF_NORMED']
for i, method_name in enumerate(methods):
img_draw = img.copy()
method = eval(method_name)
res = cv2.matchTemplate(img, template, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
print(method_name, min_val, max_val, min_loc, max_loc)
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
match_val = min_val
else:
top_left = max_loc
match_val = max_val
bottom_right = (top_left[0] + tw, top_left[1] + th)
cv2.rectangle(img_draw, top_left, bottom_right, (0,0,255),2)
cv2.putText(img_draw, str(match_val), top_left, cv2.FONT_HERSHEY_PLAIN, 2,(0,255,0), 1, cv2.LINE_AA)
cv2.imshow(method_name, img_draw)
cv2.waitKey(0)
cv2.destroyAllWindows()