views:

813

answers:

4

I have a predefined array of rgb values. I want to be able to compare a user defined color to my array and return the closest match in Objective C.

Any help is greatly appreciated.

A: 

You could try finding the Sum-of-Squared-Differences between your predefined color and the user defined color and choose the predefined color with the minimum "distance".

E.g. suppose the user-defined color is [120 300 200] and a predefined color is [100 250 150], then the sum of squared differences and the score is:

(120-100)*(120-100) + (300-250)*(300-250) + (200-150)*(200-150) = 5400 - and choose the prefefined color with the least difference.

Jacob
Thanks Jacob. Can I store the UIColor value for each predefined color and perform a closest comparison based on it's float value?
yesimarobot
Yes, you can do that. If you want to make it very fast, you can build a KD-tree from the predefined colors - this will make the querying very fast. Else, you could do it a la bruteforce - compare each color.
Jacob
Cool. I'm looking at less than 1000 comarisons max. I implemented your suggestion in php an it works well. I'm looking to implement this for the iPhone. Is a KD tree worth mytime?
yesimarobot
The trade-off is the time taken to build a KD-tree as opposed to the number of times you query it. I suggest implementing the naive method first and if it's slow, think about a KD-tree.
Jacob
+1  A: 

This begs the question or what closeness in colors is.

You will need to try this, colors are not all math. If one want to find the distance between two points in 3D space (there are three colors) the math given color1 and color2 would be: ((r2-r1)^2 + (b2-b2)^2 + (g2-g1)^2)^0.5 (the final square root is not necessary for comparison purposes).

Possible a better way would be to do the calculations in HSB space, possible just looking at Hue.

zaph
A: 

First, you should define a distance function. The trivial one is a vector length function: sum of sq. of difference by all dimensions.

Then just run through your array and select the closet one (with minimal distance).

Elalfer
+2  A: 

You need to decide in what colour space you are testing.

HSL is arguably a better colour space than RGB because you can give more weight to "hue difference" and less to "lightness". In RGB space you need to skew your differences because the eye is better at discerning shades of green than other colours.

Jeff