PyAutoGui.pixelMatchesColor() returns impossible v

2019-07-28 07:29发布

I am creating a program to draw pictures on this site, using PyAutoGui to move the mouse, click, and check some pixel colours on the screen. You can see my testing in the top left hand corner of the canvas. My program relies heavily on the pyautogui.pixelMatchesColor() function, and at certain points my program seemed to break. After trying to find the smallest set of code which would result in the same problem, I got to this:

import pyautogui
no = 0
while True:
    if pyautogui.pixelMatchesColor(1750, 180, (255, 255, -1)):
        break
    num += 1
print(num)

This, as you may have guessed outputted:

10000

The problem here is that once you have used the function more than 10,000 times in one run, it stop working and only returns:

(255, 255, -1)

I have looked around, but can't find anything anywhere on a usage limit of 10,000 for the pyautogui.pixelMatchesColor() function (btw this limit also applies to the pyautogui.pixel() function). It has broken my program, so if you have any information, or a way to circumvent this issue then please let me know. Thank you!

EDIT: After looking into the pyautogui code, it turns out it uses ctypes for mouse controls and PIL for screen utilities. I will try using them instead of pyautogui for more direct code to see if it makes a difference.

2条回答
对你真心纯属浪费
2楼-- · 2019-07-28 08:04

This might provide insight into this bug. I ran, pyautogui.pixel() until it breaks. I then tried the workaround suggested by viddle...

from PIL import ImageGrab

pixelRGB = ImageGrab.grab().getpixel((100, 125))

Which raised the following exception

Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
ImageGrab.grab().getpixel((140,20))

Traceback (most recent call last): File "", line 1, in ImageGrab.grab().getpixel((140,20)) File "C:\Users\XisUnknown\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\ImageGrab.py", line 41, in grab size, data = grabber() OSError: screen grab failed

查看更多
何必那么认真
3楼-- · 2019-07-28 08:07

For anyone else encountering this bug, I've found a workaround. Instead of calling pyautogui's pixel(x, y) function (which is just a wrapper for ImageGrab's functions), call ImageGrab.grab().getpixel((x, y)) directly. The 10.000 limit is ONLY for the pyautogui.pixel(x, y) function. I don't really know why tho...

from PIL import ImageGrab

pixelRGB = ImageGrab.grab().getpixel((x, y))

Here is a screenshot of my tests with ImageGrab.grab() vs. pyautogui.pixel() (I called ImageGrab.grab() twice as often as pyautogui.pixel())

ImageGrab.grab() fail after about 10k tries of pyautogui.pixel()

And here a screenshot of ONLY ImageGrab.grab().getpixel() calls, I cancelled after x minutes, but it doesn't seem to have a limit.

ImageGrab.grab() without pyautogui.pixel() calls inbetween

Tested on:

  • Python 3.6.3
  • Pillow 6.0.0 (PIL)
  • PyAutoGUI 0.9.42
查看更多
登录 后发表回答