0

How would I be able to get the RGB value of a pixel on my screen live with python? I have tried using

from PIL import ImageGrab as ig
while(True):
    screen = ig.grab() 
    g = (screen.getpixel((358, 402))) 
    print(g)

to get the value but there is noticeable lag.

Is there another way to do this without screen capturing? Because I think this is the cause of lag. Is there a way to drastically speed up this process?

is it possible to constrain the ig.grab() to 358, 402 and get the values from there?

  • 4
    Possible duplicate of [Get RGB value from screen pixels with python](https://stackoverflow.com/questions/42636933/get-rgb-value-from-screen-pixels-with-python) – msi_gerva Sep 14 '18 at 11:45

2 Answers2

0

The following change will speed up it by 15%

pixel = (358, 402)
pixel_boundary = (pixel + (pixel[0]+1, pixel[1]+1))
g = ig.grab(pixel_boundary)
return g.getpixel((0,0))

Runtime:

  • proposed: 383 ms ± 5.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

  • original: 450 ms ± 5.31 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Emmet B
  • 4,843
  • 6
  • 32
  • 46
0

You will probably find it faster to use mss, which is specifically designed to provide high speed screenshot capabilities in Python, and can be used like so:

import mss

with mss.mss() as sct:
    pic = sct.grab({'mon':1, 'top':358, 'left':402, 'width':1, 'height':1})
    g = pic.pixel(0,0)

See the mss documentation for more information. The most important thing is that you want to avoid repeatedly doing with mss.mss() as sct but rather re-use a single object.

Jack Aidley
  • 18,380
  • 6
  • 41
  • 69
  • How would you incorporate this so it provides live data on the RGB value of the pixel? I edited my question so mine outputs the RBG value constantly, how would you do it with this? –  Sep 14 '18 at 13:11
  • @JimboNuggets: Add a loop, and likely some kind of sleep call to stop it completely hogging the processor. – Jack Aidley Sep 14 '18 at 14:37