Archived

This topic is now archived and is closed to further replies.

Finding the closest color

This topic is 6346 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok, so I''ve got this array of 256 colors (type RGBQUAD). What algorithm should I use to, in this array, find the absolutely closest color to ANY color? Thanks for your time! /mr BiCEPS

Share this post


Link to post
Share on other sites
    
RGBQUAD Colors[256];

int FindClosest(RGBQUAD rgb)
{
int iIndexFound = -1;
int iDifferenceFound = 100000;
for(int i=0; i<256; i++)
{
int iDifference =
abs(Colors<i>.rgbRed - rgb.rgbRed) +
abs(Colors[i].rgbGreen - rgb.rgbGreen) +
abs(Colors[i].rgbBlue - rgb.rgbBlue);
if (iDifference < iDifferenceFound)
{
iIndexFound = i;
iDifferenceFound = iDifference;
}
}
return iIndexFound;
}


Share this post


Link to post
Share on other sites
Hmm, why does this algorithm looks familiar?

Sludge Software
www.sludgesoft.com
Developing a secret of mana style role-playing-game

Share this post


Link to post
Share on other sites
Ah, yes, Baskuenen''s code finds the index of the color with the same *brightness* ,not necessarily the same colour.

(I KNOW, I had this problem too)

FReY

Share this post


Link to post
Share on other sites
Baskuenen''s code is calculating the Manhattan distance (it''s really called like that) of two colors. Another way would be to use Euclidian distance ... sqrt((r1-r2)^2 + (g1-g2)^2 +(b1-b2)^2)

The problem is ... there is no ''correct'' way. Both ways of calculating the distance are valid. You might even go further and really use the brightness weighting of the RGB components to get better results:

distance = 0.3 * abs(r1-r2) + 0.6 * abs(g1-g2) + 0.1 * abs(b1-b2)

In the end, whatever works is good ... not a good answer, but so very close to the truth.

MK42

Share this post


Link to post
Share on other sites