Files
zjsh_yolov11/tool/1/find.py
琉璃月光 67883f1a50 最新推送
2026-03-10 14:14:14 +08:00

43 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import cv2
import numpy as np
def template_matching_visualization(original_image_path, template_image_path):
# 读取原始图像和模板图像
img = cv2.imread(original_image_path)
template = cv2.imread(template_image_path)
# 确认模板大小为64x64如果不是请调整
if template.shape[0] != 64 or template.shape[1] != 64:
print("警告模板图像尺寸不是64x64")
# 执行模板匹配,采用的方法是平方差匹配 method=cv2.TM_SQDIFF
result = cv2.matchTemplate(img, template, cv2.TM_SQDIFF_NORMED)
# 寻找最匹配的位置
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
# 获取匹配位置的左上角坐标
top_left = min_loc
h, w = template.shape[:2]
# 计算右下角坐标
bottom_right = (top_left[0] + w, top_left[1] + h)
# 在原图上绘制矩形框显示匹配到的位置
cv2.rectangle(img, top_left, bottom_right, (0, 255, 0), 2)
# 显示结果图像
cv2.imshow("Matched Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
return top_left, bottom_right
# 调用函数并传入原图和子图路径
original_image_path = '1.jpg'
template_image_path = '12.jpg'
position = template_matching_visualization(original_image_path, template_image_path)
print("匹配位置的左上角坐标: ", position)