是否可以pyscreeze.locate(needleImage,haystackImage):每次都不从文件中读取haystackImage?

2024-09-30 08:29:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有没有办法避免每次都读heystackImage?如果没有,除了使用BuffereImage的pyautogui/pyscreeze定位函数外,还有其他方法吗

...
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

Tags: key函数returnpngstartlocatenextconfidence
1条回答
网友
1楼 · 发布于 2024-09-30 08:29:41

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数组加载,这需要额外的处理

相关问题 更多 >

    热门问题