I faced the same problem recently, and compared various algorithms I found online. At first I was hesitant to use CIELAB color space due to its complexity, but it's really not as bad as it looks at first. Here's all the code you'll need to compare two RGB values.
struct CIELAB {
float L, a, b;
};
float gammaCorrect( float v )
{
return 100.0f * (v <= 0.04045f ? v / 12.92f : powf( (v + 0.055f) / 1.055f, 2.4f ));
}
float nonlinearToLinear( float v )
{
return v > 0.008856f ? cbrtf( v ) : 7.787f * v + 16.0f / 116.0f;
}
CIELAB RGBToCIELAB( int R, int G, int B )
{
float red = gammaCorrect( R / 255.0f );
float green = gammaCorrect( G / 255.0f );
float blue = gammaCorrect( B / 255.0f );
float xr = nonlinearToLinear( (red * 0.4124564f + green * 0.3575761f + blue * 0.1804375f) / 95.047f );
float yr = nonlinearToLinear( (red * 0.2126729f + green * 0.7151522f + blue * 0.0721750f) / 100.000f );
float zr = nonlinearToLinear( (red * 0.0193339f + green * 0.1191920f + blue * 0.9503041f) / 108.883f );
return { 116.0f * yr - 16.0f, 500.0f * (xr - yr), 200.0f * (yr - zr) };
}
float similarity( int R0, int G0, int B0, int R1, int G1, int B1 )
{
CIELAB lab0 = RGBToCIELAB( R0, G0, B0 );
CIELAB lab1 = RGBToCIELAB( R1, G1, B1 );
float dL = lab0.L - lab1.L;
float da = lab0.a - lab1.a;
float db = lab0.b - lab1.b;
return dL*dL + da*da + db*db;
}
For the similarity() function, the lower the result the better the match. For improved efficiency, pre-convert your RGB color list into CIELAB space.
If a simpler algorithm is desired, Wikipedia's Color difference page has an algorithm that works pretty well. You can implement it using integer arithmetic, and if only comparing similarities you can skip the square-root computation.
int similarity( int R0, int G0, int B0, int R1, int G1, int B1 )
{
int dr = R0 - R1;
int dg = G0 - G1;
int db = B0 - B1;
int redsum = R0 + R1;
return (1024 + redsum) * dr*dr + 2048 * dg*dg + (1534 - redsum) * db*db;
}
The computation will not exceed 32-bit signed integers.
I found this matching to be noticeably inferior to matching in CIELAB space, but the computation is trivial.
I also tried matching in HSV color space but did not get good results for some color pairs. For example, pure white and pure black (which are as different as can be) can have the same hue and saturation, so might match better than you'd like.