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]

# 设置匹配的阈值(相似度越接近1越相似)
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()