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
| import cv2 import numpy as np
img = cv2.imread('image.jpg', 0) template = cv2.imread('template.jpg', 0) img_color = cv2.cvtColor(img.copy(), cv2.COLOR_GRAY2BGR)
t_height, t_width = template.shape[:2]
scale_factors = [0.5, 0.75, 1.0, 1.25, 1.5]
threshold = 0.8
for scale in scale_factors: resized_template = cv2.resize(template, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR) rt_height, rt_width = resized_template.shape[:2]
if rt_height > img.shape[0] or rt_width > img.shape[1]: continue
result = cv2.matchTemplate(img, resized_template, cv2.TM_CCOEFF_NORMED)
y_coords, x_coords = np.where(result >= threshold)
for (x, y) in zip(x_coords, y_coords): top_left = (x, y) bottom_right = (x + rt_width, y + rt_height) cv2.rectangle(img_color, top_left, bottom_right, (0, 255, 0), 2) score = result[y, x] print(f"Scale: {scale:.2f}, Match Score: {score:.4f}, Position: {top_left}")
cv2.imshow('Multi-match Template Matching', img_color) cv2.waitKey(0) cv2.destroyAllWindows()
|