Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding nearest RGB colour

Tags:

c++

colors

rgb

I was told to use distance formula to find if the color matches the other one so I have,

struct RGB_SPACE
{
    float R, G, B;
};

RGB_SPACE p = (255, 164, 32);  //pre-defined
RGB_SPACE u = (192, 35, 111);  //user defined

long distance = static_cast<long>(pow(u.R - p.R, 2) + pow(u.G - p.G, 2) + pow(u.B - p.B, 2));

this gives just a distance, but how would i know if the color matches the user-defined by at least 25%?

I'm not just sure but I have an idea to check each color value to see if the difference is 25%. for example.

float R = u.R/p.R * 100;
float G = u.G/p.G * 100;
float B = u.B/p.B * 100;

if (R <= 25 && G <= 25 && B <= 25)
{
   //color matches with pre-defined color.
}
like image 562
user963241 Avatar asked Nov 13 '10 07:11

user963241


1 Answers

I would suggest not to check in RGB space. If you have (0,0,0) and (100,0,0) they are similar according to cababungas formula (as well as according to casablanca's which considers too many colors similar). However, they LOOK pretty different.

The HSL and HSV color models are based on human interpretation of colors and you can then easily specify a distance for hue, saturation and brightness independently of each other (depending on what "similar" means in your case).

like image 162
Philipp Avatar answered Nov 02 '22 19:11

Philipp