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)