Get Viewport Pixel Color Value At Mouse Cursor Location?

Given a real-time cursor location from a MouseCallback, how does one implement the Color Picker Eye Dropper directly in scripting or another method to return the pixel color value at cursor location without calling the Color Picker UI and needing to manually select the Eye Dropper?

Here’s an example of what the interaction looks like that I want to call directly in code without the UI:

The goal is to simply return the color value at the mouse cursor location while the callback is active.

Thank you for your help!

Hi,

import clr
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
from System.Windows.Forms import Cursor
from System.Drawing import Bitmap, Graphics, Rectangle
from System.Threading import Thread, ThreadStart

def get_pixel_color(x, y):
    bitmap = Bitmap(1, 1)
    graphics = Graphics.FromImage(bitmap)
    graphics.CopyFromScreen(x, y, 0, 0, bitmap.Size)
    color = bitmap.GetPixel(0, 0)
    return (color.R, color.G, color.B)

def main():
    try:
        while True:
            x, y = Cursor.Position.X, Cursor.Position.Y
            color = get_pixel_color(x, y)
            print "RGB Color at ({0},{1}): {2}".format(x, y, color)
            Thread.Sleep(100)  # Sleep for 100 milliseconds
    except KeyboardInterrupt:
        print "Program exited."

if __name__ == '__main__':
    main()

Hope this sparks your imagination,
Farouk

1 Like

Awesome thank you so much @farouk.serragedine ,

That works great after I adapted it for the code I’m working in.

Here’s the use case:

@michaelvollrath
I’m impressed, that utility thing you did there is honestly great. Good job there.
Would you mind sharing the object shower on mouse hover?
I really like it and would love to do something similar, I believe your work could save me a few hours at least !
If not It’s fine :slight_smile:

Hi @farouk.serragedine ,

I’ll clean up the code and keep you posted when I share

EDIT:

Here you go @farouk.serragedine , for what it’s worth to you: