最近我开始为魔兽世界(3.3.5)游戏编写一个机器人,为此我必须了解cv2,但我仍然不明白它,下面是代码:
import cv2
import numpy as np
import os
screenshot = cv2.imread('scren.png')
template_folder = 'tem_1'
templates = [cv2.imread(os.path.join(template_folder, f))
for f in os.listdir(template_folder) if f.endswith('.png')]
threshold = 0.8
coordinates = []
def are_points_close(pt1, pt2, threshold_distance=40):
return np.linalg.norm(np.array(pt1) - np.array(pt2)) < threshold_distance
for template in templates:
result = cv2.matchTemplate(
screenshot, template, cv2.TM_CCOEFF_NORMED)
loc = np.where(result >= threshold)
# Отметьте найденные шаблоны
for pt in zip(*loc[::-1]): # Переворот координат
cv2.rectangle(
screenshot, pt, (pt[0] + template.shape[1], pt[1] + template.shape[0]), (0, 255, 255), 2)
coordinates.append((pt))
print(coordinates)
cv2.imwrite('output.png', screenshot)
cv2.imshow('Detected Templates', screenshot)
cv2.waitKey(0)
cv2.destroyAllWindows()
它会在屏幕上圈出模板并显示其坐标以供进一步迭代,但代码返回给我:
np.int64(575)), (np.int64(1427), np.int64(575)), (np.int64(1428), np.int64(575)), (np.int64(1427), np. int64(576)), (np.int64(1654), np.int64(689)), (np.int64(1655),np.int64(689)),(np.int64(1656),np.int64(689)),(np.int64(1655),np.int64(690)),(np .int64(1655), np.int64(404....
一切看起来都很正常,但关键是屏幕上只有4 个东西,而且有很多坐标,它们相差1-3个值,机器人找到东西并选择它们,但不知何故它得到了太多他们。
前三个是模板,然后是屏幕,以及机器人找到的内容。
事实上loc并不包含相关函数的最大值,而是包含它周围的一些区域(阈值越低,这个区域越大)。
选项一:以某种方式将附近点的坐标组合成簇。
选项二:简单地找到连接区域的质心:
结果: