How to extract the brightness value from a color?

or getting the red, green, blue colors from a color.

what exactly do you mean, a ‘color’? Do you mean the internal ofColor type? or a hex value, e.g. 0x2F7A83.

To get r,g,b from an ofColor is very simple, you just use the r, g, b properties:

ofColor myColor;  

to get the r,g,b (and a) components from a hex value has slightly more to it:

int myColor = 0x2F7A83;  
int r = (myColor >>16) & 255;  
int g = (myColor >> 8) & 255;  
int b = (myColor) & 255;  
int a = (myColor >> 24) & 255;  

these return in the range 0…255

To get the brightness of a pixel you can just average the r, g and b components. But for a more accurate perceptive brightness value you can use the formula:
(0.2126*r) + (0.7152*g) + (0.0722*b)

A fun article about why:

Great response, Memo – but sometimes I wish there was just be an analogue to Processing’s “brightness()”. :slight_smile:

I’ve written a more complex color addon you might consider using:">color]

I didn’t realize, but it doesn’t use ofColor directly. Still, you could do this:

ofColor myColor;  
ofxColor betterColor(myColor.r, myColor.g, myColor.b);  
float brightness = betterColor.brightness;  

Hey kyle, why not extend ofColor so it’s backwards compatible? Thats what I did with msaColor :wink: so you can do

msaColor myColor;  

The original reason I didn’t extend ofColor is because I was working with HSB rather than HSV, and it wouldn’t have worked to have two variables name “b” that meant different things.

I suppose I could, now – good idea :slight_smile: Though I do like the whole-name variables (red, green blue, etc.) as opposed to the short ones (r, g, b).

Thanks for the reply!

a little vote for rolling msacolor into core.
myColor = ofColor(1,2,3,4)

to my eyes there’s not so much point in having a color class unless you can easily declare and operate on a color.


just a little observation:
To get the rgb components I needed to convert the results to int:

cout << " color r: " << (int)colorRama.r << endl;
cout << " color g: " << (int)colorRama.g << endl;
cout << " color b: " << (int)colorRama.b << endl;