import cv2 import numpy as np # 加载游戏截图图像 image = cv2.imread('detect_tigers/MuMu12-20240922-131314.png') # 转换为灰度图 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 加载大力虎的模板图像(你需要准备一个小的模板图像,含有大力虎的外观) template = cv2.imread('detect_tigers/dalihu1.png', 0) # 模板应该是灰度图 w, h = template.shape[::-1] # 进行模板匹配 result = cv2.matchTemplate(gray_image, template, cv2.TM_CCOEFF_NORMED) # 设置匹配阈值,值越高匹配越严格 threshold = 0.5 locations = np.where(result >= threshold) # 容差值:合并相近的坐标时使用 tolerance = 5 # 初始的 Y 和 X 坐标数组 y_coords = locations[0] x_coords = locations[1] # 存储过滤后的 Y 和 X 坐标 filtered_coords = [] # 遍历坐标,去重并合并相近的值 for i in range(len(y_coords)): # 如果过滤后的列表为空,或者当前坐标和最后一个存储的坐标相差大于容差值,则将其加入 if not filtered_coords or (abs(y_coords[i] - filtered_coords[-1][1]) > tolerance or abs(x_coords[i] - filtered_coords[-1][0]) > tolerance): filtered_coords.append((x_coords[i], y_coords[i])) # 打印过滤后的坐标 for coord in filtered_coords: print(f"X: {coord[0]}, Y: {coord[1]}") # 在原图上标出匹配的位置 cv2.rectangle(image, coord, (coord[0] + w, coord[1] + h), (0, 255, 0), 2) # 显示匹配结果 cv2.imshow('Detected Tigers', image) cv2.waitKey(0) cv2.destroyAllWindows() # python detect_tigers.py