首页 > 解决方案 > pyautogui.locatecenteronscreen() 的 opencv python 替代方案,仅用于图像而不是屏幕

问题描述

我想知道如何在 python 中使用 opencv (cv2) 来替代 pyautogui.locatecenteronscreen() 函数,只使用图像而不是屏幕。我会尝试使用一个例子。

也许是一个用户定义的函数,locateCenterOfTemplate("Path/to/template.png") 现在因为我使用屏幕截图作为原始图像,所以它就像我使用 pyautoguis 一样,但对于我的主要目的我不会.

import cv2
import pyautogui

pyautogui.screenshot(Path/to/original_image.png)

def locateCenterOfTemplate(image, template, accuracy=100,
region=#whole screen idk how to do this eaither):


temp = locateCenterOfTemplate("Path/to/original_image.png", "Path/to/template.png")
# now variable "temp" is the same as the posision of the center of the template,
# inside of the source immage
pyautogui.click(temp)

基本上,我希望将模板与区域、置信度以及模板和原始图像作为功能匹配:)

感谢:D

标签: python-3.xopencvcv2template-matching

解决方案


如果您使用cv2.imread(path). 您可以使用cv2.matchTemplate。不久前,我使用此代码匹配屏幕上的所有模板,置信度高于threshold. 您可以使用debug=True, 在找到的模板周围绘制一个红色框(cv2 使用 BGR)。

 def match_all(image, template, threshold=0.8, debug=False, color=(0, 0, 255)):
        """ Match all template occurrences which have a higher likelihood than the threshold """
        width, height = template.shape[:2]
        match_probability = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
        match_locations = np.where(match_probability >= threshold)

        # Add the match rectangle to the screen
        locations = []
        for x, y in zip(*match_locations[::-1]):
            locations.append(((x, x + width), (y, y + height)))

            if debug:
                cv2.rectangle(image, (x, y), (x + width, y + height), color, 1)
        return locations

它将返回匹配区域的边界框列表。如果您只想返回最高匹配,则应将该match_locations行调整为:

match_location = np.unravel_index(match_probability.argmax(), match_probability.shape)

或者,如果您可以使用另一个库,您可以查看 Multi-Template-Matching,它返回一个带有模板名称、边界框和分数的 pandas DataFrame。


推荐阅读