python - Python OpenCV在元组中追加匹配的中心x,y坐标

标签 python opencv

我有这个用Python编写的简单opencv模板匹配功能。

图片:enter image description here

模板:enter image description here

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)

它将正确找到所有模板,如下所示:enter image description here

但是,我的目标是在函数外部传递要在循环中使用的中心坐标。为此,我需要将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)]

enter image description here

关于python - Python OpenCV在元组中追加匹配的中心x,y坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61687427/

相关文章:

python - str.replace 从 pandas DataFrame 的后面开始

python - CSV 文件和 Python

python - 在 Maya 中使用 Python 引用结果

xcode - cvCreateTrackbar()不起作用

python-3.x - 如何使用opencv python查找图像中的最小矩形?

Python 3 - Pycrypto - 只读固定缓冲区

javascript - 登录 Python 和 Django 应用程序时本地服务器出现错误

c++ - openCV中的Absdiff可以编译但显示黑色图像

python - 如何裁剪轮廓的内部区域?

python - 从 NumPy 数组中删除值对