Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if a color is closer to white or black?

Tags:

I am dealing with images and would like to determine if a set of pixels are closer to white or black.

So given a set of colors/pixles, how does one determine if they closer to a white or a black?

I have tried some noobish algorithms, does anyone know how I can do this?

like image 214
Aziz Avatar asked Mar 20 '12 02:03

Aziz


2 Answers

I would say that you can first convert the color to gray scale and then check if it's nearer to black or white.

First convert the RGB color value to compute luminance by the following formula

Y = 0.2126*R + 0.7152*G + 0.0722*B

Then check if the value is nearer to 0 or to 255 and choose black or white accordingly

color c = Y < 128 ? black : white

Mind that this works well if the color space is not gamma compressed, otherwise you will have to add a step before calculating the luminance which is a gamma expansion, compute Y, then perform a gamma compression to obtain a non-linear luminance value that you can then use to decide if color is nearer to black or white.

like image 89
Jack Avatar answered Oct 12 '22 13:10

Jack


Take a look at YCbCr. Since Java and most computer processes colors in RGB format, you will need to do some conversion from RGB to YCbCr. There are many formulas to convert RGB to YCbCr.

Once you get the YCbCr value, you can check the luminance value (the value Y in YCbCr).

like image 34
mauris Avatar answered Oct 12 '22 11:10

mauris