finding closest image colors

I am making a program that loads an image and saves a version that only uses the colors in a pallet. What is the best algorithm to use to match the pixels to the nearest color in the pallet?
[197 byte] By [@@aa@@--@-@aa@@a] at [2007-10-3 2:38:28]
# 1
I don't think you'll get an objective answer to that question. Even subjective answers probably depend on your precise aims.
YAT_Archivista at 2007-7-14 19:36:44 > top of Java-index,Other Topics,Algorithms...
# 2

YAT is correct, there will be little agreement on the notion of "best"

But looked at differently, choose any method you like and you can argue that it is the best.

A typical algorithm is Euclidean distance

i.e. min((R-r)*(R-r) + (G-g)*G-g) + (B-b)*(B-b))

where r,g,b is your given color and R,G,B range over the values in the pallet.

You could do the same calculation in HLS space. And many of the varients consist of including a multiplicative factor on each of the terms so that for example you consider difference in Blue to be worse that difference in Red, or you weight mismatch in Saturation more than Hue.

Choose anything, try it, try some variants and choose the one that you think fits your application.

marlin314a at 2007-7-14 19:36:44 > top of Java-index,Other Topics,Algorithms...
# 3

"Closest" depends on things like the fact that the human eye is less sensitive to shades of blue but very sensitive to changes in green/yellow intensity. "Closest" comes down to things like what brand of screen the user is looking at.

For a rough overview of algorithms in this area, google for things like "printer/photograph color matching".

Paul_Murraya at 2007-7-14 19:36:44 > top of Java-index,Other Topics,Algorithms...
# 4

You won't know what works till you try it!

1) Have some pallette class if java doesn't already have one (probably does).

2) Iterate through each element while retrieving it's RGB components

3) Compare each real picture color to a pallette color

4) setup some if statement saying

if ( real_color.isClosestToThisColorInPallette( palleteObject.getColor()) == true )

{

SaveAsThisColor( palleteObject.getColor() );

}

Many loops are required. But a computer can handle it. And because its only for the saving process, the speed doesn't matter. it should take about 0.5 seconds anyway.

AK47_prga at 2007-7-14 19:36:44 > top of Java-index,Other Topics,Algorithms...