python-3.x - 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
解决方案
如果您使用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。
推荐阅读
- arduino - 数字引脚为高电平时 Arduino 休眠
- html - CSS font-face 规则未在 Firefox 中的选择选项上呈现
- python - 如何从 csv 文件创建的列表中获取基本统计信息,例如总和、平均值、中值、最大值和最小值
- javascript - 停止打开容器外的用户交互
- python - 内核似乎已经死机,它将自动重新启动 - JUPYTER 笔记本
- java - Java程序未在cmd中运行
- javascript - 如何使用 javascript 在“element.classList.add”中切换“添加”以删除
- c# - 如何优雅地停止定时后台任务
- laravel - 如何结合这两个条件?在 laravel 中
- javascript - react.js typescript spread(...) 仅添加最后一个元素