我有这个用Python编写的简单opencv模板匹配功能。
图片:
模板:
def find(object, sensitivity):
screen = "tool.png"
screen_read = cv2.imread(screen)
screen_gray = cv2.cvtColor(screen_read, cv2.COLOR_BGR2GRAY)
obj = cv2.imread(object, cv2.IMREAD_GRAYSCALE)
w, h = obj.shape[::-1]
location = np.where(cv2.matchTemplate(screen_gray, obj, cv2.TM_CCORR_NORMED) >= sensitivity)
positions = []
for xy in zip(*location[::-1]):
cv2.rectangle(screen_read, xy, (xy[0] + w, xy[1] + h), (0, 0, 255), 1)
x = random(xy[0], (xy[0] + w) - 2)
y = random(xy[1], (xy[1] + h) - 2)
print(x, y)
positions.append(str(x) + ", " + str(y))
#cv2.imshow("Test", screen_read)
#cv2.waitKey(0)
find("enemylogo.png", 0.90)
它将正确找到所有模板,如下所示:
但是,我的目标是在函数外部传递要在循环中使用的中心坐标。为此,我需要将x,y坐标存储为数组(位置)作为元组。
但是,我没有得到理想的结果,它添加了太多的元组,而不是仅仅添加了2个。
我想做的是:
for x in find("enemylogo.png", 0.90):
click(x) #x would be the coordinate of every template matched.
有人可以帮我吗?
最佳答案
location = np.where....
行将为您提供许多匹配项,其中许多将彼此相邻。另一种技术是递归使用minMaxLoc。此功能只会给您最好的结果。但是,如果您在第一次通过时用零覆盖最佳匹配,则第二次通过将找到另一个匹配。
import cv2
import numpy as np
def find_templates(obj, sensitivity):
image = cv2.imread('tool.png', cv2.IMREAD_COLOR )
template = cv2.imread(obj, cv2.IMREAD_COLOR)
h, w = template.shape[:2]
print('h', h, 'w', w)
method = cv2.TM_CCORR_NORMED
threshold = 0.90
res = cv2.matchTemplate(image, template, method)
res_h, res_w = res.shape[:2]
# fake out max_val for first run through loop
max_val = 1
centers = []
while max_val > sensitivity:
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if max_val > sensitivity:
centers.append( (max_loc[0] + w//2, max_loc[1] + h//2) )
x1 = max(max_loc[0] - w//2, 0)
y1 = max(max_loc[1] - h//2, 0)
x2 = min(max_loc[0] + w//2, res_w)
y2 = min(max_loc[1] + h//2, res_h)
res[y1:y2, x1:x2] = 0
image = cv2.rectangle(image,(max_loc[0],max_loc[1]), (max_loc[0]+w+1, max_loc[1]+h+1), (0,255,0) )
print(centers)
cv2.imwrite('output.png', image)
find_templates("enemy_logo.png", 0.90)
这使
[(52, 52), (169, 52)]
关于python - Python OpenCV在元组中追加匹配的中心x,y坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61687427/