'How to use PyAutoGUI to detect RGB values

I'm trying to build a small bot that clicks only certain colours. I believe pyautogui.displayMousePosition() should display the position of my mouse as well as the RGB values of the pixel the mouse is on. Instead, I'm only seeing the positional values (seen in the screenshot). Could this be an issue with MacOS?

No RGB values being displayed on python console - screenshot

Would also love to know if there's an alternate way I can go about this.



Solution 1:[1]

displayMousePosition() is the wrong function to be using for pretty much anything besides validating that the library is functioning correctly. It doesn't return any values, all it does is print information to console. I'd strongly suggest browsing pyautogui's documentation to find out more about the functionality the library provides.

Assuming you know the screen x and y coordinates you are wanting to get the color of you'll want to take a screenshot of the screen and inspect the color values at the appropriate location.

im = pyautogui.screenshot()
px = im.getpixel((x, y))

There is a wrapper that lets you get pixel information from a coordinate pair that you can use as well.

px = pyautogui.pixel((x, y))

Solution 2:[2]

Here is the code to check mouse point pixel:

import pyautogui
import time

while 1:
    x, y = pyautogui.position()
    r,g,b = pyautogui.pixel(x, y)
    print(r,g,b)
    #time.sleep(0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sphennings
Solution 2