Search code examples
linuxshellx11gtk3

How to get the value of a pixel from the screen (GTK 3, Shell, Linux)


I am trying to do some automation on Linux, and I can't find a good way to get a pixel value from the screen, given 2 coordinates.

I have this python code:

#!/usr/bin/env python3
import pyautogui
import sys

image = pyautogui.screenshot()
print(str(image.getpixel((int(sys.argv[1]), int(sys.argv[2])))))

How can I do this without taking a screenshot and instead read from the pixel buffer?

If there is a program that someone knows about that can do this (I've heard AutoHotkey on windows can), that would also be helpful, as I'm using shell script (and lots of xdotool) to do the automation.


Solution

  • The following code, when called like this: ./getColor.py [X coordinate] [Y coordinate], will print the decimal RGB color value of the specified pixel on the screen in the form (R, G, B)

    #!/usr/bin/python
    import gi, sys
    gi.require_version('Gdk', '3.0')
    from gi.repository import Gdk
    pixbuf = Gdk.pixbuf_get_from_window(Gdk.get_default_root_window(), int(sys.argv[1]), int(sys.argv[2]), 1, 1)
    print(tuple(pixbuf.get_pixels()))