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.
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.
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.
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.
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).
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.