如何在 Python 中快速定位屏幕上的内容?

新手上路,请多包涵

我试过使用 pyautogui 模块和我在屏幕上定位图像的功能

pyautogui.locateOnScreen()

但它的处理时间约为 5-10 秒。有没有其他方法可以让我更快地在屏幕上定位图像?基本上,我想要一个更快的 locateOnScreen() 版本。

原文由 Darth Vador 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

官方文档 说在 1920x1080 的屏幕上应该需要 1-2 秒,所以你的时间似乎有点慢。我会尝试优化:

  • 除非颜色信息很重要,否则使用灰度( grayscale=True 应该提供 30% 左右的加速)
  • 使用较小的图像来定位(如果这已经唯一标识了您需要获得的位置,则仅作为一部分)
  • 不要在每次新的时候加载你需要从文件中定位的图像,而是将它保存在内存中
  • 如果您已经了解可能的位置(例如,从以前的运行中),请传入区域参数

这一切都在上面链接的文档中进行了描述。

这仍然不够快吗,您可以检查 pyautogui 的来源,看到屏幕上的定位使用在 Python 中实现的特定算法(Knuth-Morris-Pratt 搜索算法)。所以在 C 中实现这部分,可能会导致相当明显的加速。

原文由 Trilarion 发布,翻译遵循 CC BY-SA 3.0 许可协议

制作一个函数并使用线程信心(需要opencv)

 import pyautogui
import threading

def locate_cat():
    cat=None
    while cat is None:
        cat = pyautogui.locateOnScreen('Pictures/cat.png',confidence=.65,region=(1722,748, 200,450)
        return cat

如果您知道它在屏幕上的大致位置,则可以使用区域参数

在某些情况下,您可以在屏幕上定位并将该区域分配给一个变量,并使用 region=somevar 作为参数,这样它看起来就在上次找到它的同一个地方,以帮助加快检测过程。

例如:

 import pyautogui

def first_find():
    front_door = None
    while front_door is None:
        front_door_save=pyautogui.locateOnScreen('frontdoor.png',confidence=.95,region=1722,748, 200,450)
        front_door=front_door_save
        return front_door_save

def second_find():
    front_door=None
    while front_door is None:
        front_door = pyautogui.locateOnScreen('frontdoor.png',confidence=.95,region=front_door_save)
        return front_door

def find_person():
    person=None
    while person is None:
        person= pyautogui.locateOnScreen('person.png',confidence=.95,region=front_door)

while True:
    first_find()
    second_find()
    if front_door is None:
        pass
    if front_door is not None:
        find_person()

原文由 user11335084 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题