Get the screen color under the mouse pointer with grabScreen()?

I would like to get the color of the pixel that is under the mouse pointer. I thought I would be clever and just do a grabScreen() of 1x1 pixel and then do a getPixels() and get the color. It’s not working though, I get ‘chars’ instead of numbers. Any ideas?

int xMouse,yMouse;
ofImage imgTmp;
ofColor tmpColor;

imgTmp.grabScreen(xMouse,yMouse,1,1);
unsigned char *pixels=imgTmp.getPixels();

tmpColor.r = (float) pixels[0];
tmpColor.g = (float) pixels[1];
tmpColor.b = (float) pixels[2];

cout << tmpColor.r << "\n";

ofPixels contains chars since it’s an 8bit per channel image, but the value is correct, just cast it to int to print them:

cout << (int)tmpColor.r << "\n";
1 Like

I thought I was casting them into tmpColor by writing:

tmpColor.r = (float) pixels[0];
etc.

Is that not casting?

This doesn’t seem to work either (I want to get the values in tmpColor of course):

int r = (int) pixels[0];
int g = (int) pixels[1];
int b = (int) pixels[2];

tmpColor.r = r;
tmpColor.g = g;
tmpColor.b = b;

You could use the ofImage::getColor(int,int) method instead.

each ofPixels or ofColor component is an unsigned char, so a number from 0 to 255, when you do:
tmpColor.r = (float) pixels[0];

you are casting the red component of the pixel to float but storing it again in an unsigned char so it has no effect. you can just do:

tmpColor.r = pixels[0]

or as chuckleplant says just use getColor from ofPixels:

tmpColor = imgTmp.getColor(0,0)

even with that the way you were doing it should work, why do you say it’s not working? what values are you getting

When I cout or ofDrawBitmapString then the output is ascii characters and not numbers.

If I use the resulting color however it does seem to work.

as i said in the previous post you need to cast when using cout, the internal type of ofPixels or ofColor is unsigned char so when printing it it’ll print it as a char not as a number but the information is correct.

cout << (int) pixels[0] << endl;

or

cout << tmpColor << endl

or

ofDrawBitmapString(ofToString((int)pixels[0]),20,20)

or

ofDrawBitmapString(ofToString(tmpColor),20,20)

or even

ofDrawBitmapString(ofToString(imgTmp.getColor(0,0)),20,20)

the problem is on how c++ tries to print unsigned chars, as characters not as numbers but indeed the information is just a number between 0…255

1 Like

Thank you for your reply.

It’s just that when I take the unsigned char and use it to define a color and then print the value in one of the color channels it’s still printed as a char. Which confuses me. I can use the color in my program though, it seems to work fine. So I guess I don’t need to worry about it and just ‘cast’ it if I want to look at the value for debug purposes or something…

Thank you.

yes that’s because ofColor uses unsigned char as well for it’s component so you still need to do:

cout << (int)tmpColor.r << endl;

to see the components as numbers

1 Like