首页 > 解决方案 > 是否可以 pyscreez.locate(needleImage, haystackImage): 无需每次都从文件中读取 haystackImage?

问题描述

我目前正在将 PyAutoGUI 用于在 aneedleImage上搜索 a 的 locate 函数haystackImage。文档提供的示例包含图像的路径。但是,我有一个函数可以将一系列 与needleImage单个进行比较haystackImages,并且在需要检查的次数内读取相同的图像文件效率非常低。

有没有办法避免heystackImage每次都阅读?如果没有,是否有任何替代 pyautogui/pyscreez 使用 bufferedImage 的定位功能?

...
checks = {
        "recieve.png": 'recieve',
        "next.png": 'next',
        "start.png": 'start',
        "black.png": 'loading',
        "loading.png": 'loading',
        "gear.png": 'home',
        "factory.png": 'factory',
        "bathtub.png": 'bathtub',
        "refit.png": 'refit',
        "supply.png": 'supply',
        "dock.png": 'dock',

        # SPE
        "spepage.png": 'spe',
        "expeditionpage.png": 'expedition',
        "sortiepage.png": 'sortie',
        "practice.png": 'practice',
        "practiceinfo.png": 'practice',

        "oquest.png": 'quest',
        "quest.png": 'quest'
    }
    for key in checks:
        if (detect(key, cache=True)):
            return checks[key]
def detect(imgDir, confidence=0.85, cache=False):
    if (pyautogui.locate(os.path.join('images', imgDir), 'images\\capture.jpeg', confidence=confidence)) is not None:
        return True
    else:
        return False

标签: pythoncomputer-visionpyautoguipyscreeze

解决方案


pyautogui.locate()还接受 numpy 数组和 PIL 图像作为输入。您可以将 haystack 图像读入 numpy 数组 (BGR) 或 PIL 图像,然后传递它而不是文件名。

def detect(imgDir, haystackImage, confidence=0.85, cache=False):
    if (pyautogui.locate(os.path.join('images', imgDir), haystackImage, confidence=confidence)) is not None:
        return True
    else:
        return False

from matplotlib import image
hsImage = image.imread('images\\capture.jpeg')
hsImage = hsImage[:,:,::-1] # convert RGB to BGR
detect('needleImg.png', hsImage, cache=True)

# Alternate method
from PIL import Image
hsImage = Image.open('images\\capture.jpeg')
detect('needleImg.png', hsImage, cache=True)

第二种方法可能比第一种方法慢,因为pyautogui.locate()最终将 PIL 图像加载为 numpy 数组,这需要额外的处理。


推荐阅读