在使用ImageGrab检索的较大图像中检测到较小图像(.png)?

时间:2019-05-27 02:05:47

标签: python python-imaging-library

我花了一个小时来研究这个简单的主题,但是我遇到的所有答案都非常复杂,作为Python的新手,我无法将其中的任何一个合并到我的程序中。

我正在尝试让AI播放Piano Tiles Game的浏览器版本。到目前为止,我只是试图捕获游戏窗口(计算机屏幕的一小部分),然后使用游戏的开始按钮的.png来检查该游戏窗口。从那里我将继续单击“开始”按钮,但这又是一个问题。

如何检查图像是否包含.png文件?

这是我当前的代码:

from PIL import ImageGrab as ig, ImageOps as io, Image
import pyautogui
import bbox

def grabStart(window):
    #The start button
    start = Image.open("res/StartButton.PNG")
    start = io.grayscale(start)

    #This is the part I need to figure out. The following is just pseudocode
    if window.contains(start): #I know that this doesn't actually work. Just pseudocode
        #I'd like to return the location of 'start' in one of the following forms
        return either: (x1, y1, x2, y2), (x1, y1, width, height), (a coordinate within 'start'))

def grabGame():
    #The coordinates of the entire game window
    x1 = 2222
    y1 = 320
    x2 = 2850 
    y2 = 1105

    #The entire screen of the game
    window = ig.grab(bbox = (x1, y1, x2, y2))
    window = io.grayscale(window)

    return window

grabStart(grabGame())

2 个答案:

答案 0 :(得分:0)

尝试使用pyautogui.locate()。函数输入两个参数,第一个是需要查找的图像,第二个是需要查找较小图像的图像。此方法仅适用于图像,因此,如果要在实时窗口中运行此方法,则可以考虑使用其他方法。其次,pyautogui只是PIL的包装,因此,如果遇到效率问题,您可能想将locate()转换为等效的PIL以提高性能。

答案 1 :(得分:0)

这是一种方法。我只是让程序保持运行状态,然后打开/关闭,然后在屏幕上移动按钮的预览,看它是否能发现按钮并正确报告坐标。

#!/usr/bin/env python3

from PIL import ImageGrab as ig, Image
import pyautogui as ag

def checkButton(button, window):
    try:
        location = ag.locate(button, window, confidence=0.8)
        print(f'location: {location[0]},{location[1]},{location[2]},{location[3]}')
    except:
        print('Not found')

# Load button just once at startup
button = Image.open("button.png")

# Loop, looking for button
while True:
    window = ig.grab()
    checkButton(button, window)