【问题标题】:opencv python alternative for pyautogui.locatecenteronscreen(), just for an image instead of screenpyautogui.locatecenteronscreen() 的 opencv python 替代方案,仅用于图像而不是屏幕
【发布时间】:2021-03-22 06:54:33
【问题描述】:

我想知道如何在 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.x opencv cv2 template-matching


    【解决方案1】:

    如果您使用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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-15
      相关资源
      最近更新 更多