laserjagaren
laserjagaren

Reputation: 3

pyautogui.pixel(x,y) starts lagging in a while loop

I want to check when a pixel on the screen is changing and then put a keyboard event when the pixel is changing colors. But after about 2-4 min the computer slows down when pyautogui.pixel() have been called multiple times.

Here is my code

import pyautogui

OldC1 = None

while True:
   NewC1 = pyautogui.pixel(750, 550)

   if NewC1 != OldC1:
      pyautogui.press('up')

   OldC1 = NewC1;

Is there a way to get around the lag?

Upvotes: 0

Views: 2627

Answers (2)

Vasu Deo.S
Vasu Deo.S

Reputation: 1850

The problem is not that much with the function that you are using to get the values, but from the infinite loop that is running continuously at all times.

If the time precision is not required, then i would recommend putting a bottleneck on the loop cycles, via a function similar to sleep()

TRY:

from PIL import ImageGrab
import time

OldC1 = (0, 0, 0)

while True:

   time.sleep(.3)
   NewC1 = ImageGrab.grab().getpixel((750, 550))

   if NewC1 != OldC1:
      pyautogui.press('up')

   OldC1 = NewC1

The time.sleep(2) will reduce the frequency of iterations, and in turn will result into a lot better performance in the long run.

EDIT:

Instead of using pyautogui's pixel function to get a specific pixel's RGB values, I rather used getpixel() from PIL (Python Imaging Library) module, the reason is because pyautogui.pixel() function is just a wrapper of ImageGrab.grab().getpixel(), and since we are striving for performance, we should instead used getpixel() directly, for a little performance boost.

PS:

pyautogui.pixel() has a limit to total pixel lookups which is somewhere around 10,000. Read This Answer. This may lead to incorrect results, if lookup value exceed 10,000, PIL's getpixel() doesn't have this threshold value.

Upvotes: 0

viddie
viddie

Reputation: 96

I've encountered similar issues, my way of circumventing that problem was to use PIL's functions directly, instead of pyautogui's wrapper functions:

from PIL import ImageGrab

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

Using this function did not slow down my pc.

Upvotes: 2

Related Questions