• Status: Solved
• Priority: Medium
• Security: Public
• Views: 847

# find closest color in hsv space

Given an array of hsv values and one color in hsv, how would I find the closest match in the array?
0
hbiz
• 5
• 2
1 Solution

Commented:
Depends on what you mean by "closest match." Just calculate the distance for each as
``````distance[i] = abs(array[i].h - color.h)
+ abs(array[i].s - color.s)
+ abs(array[i].v - color.v))
``````
and pick the lowest.
0

Commented:
If a difference in one is more impacting that in another you could use weights.
For example if a difference in v is twice as bad as a difference in s and s and h are the same, then you could do it with
``````distance[i] = abs(array[i].h - color.h)
+ abs(array[i].s - color.s)
+ 2*abs(array[i].v - color.v))
``````
Or if you want to scale it to 0-1 (and assuming the max value of each value is 255) use this
``````distance[i] = (.25*abs(array[i].h - color.h)
+ .25*abs(array[i].s - color.s)
+ .5*abs(array[i].v - color.v))/255
``````
0

Commented:
How about treating the three HSV values as X Y and Z in 3D space.  In this case we can say we have two HSV values H1S1V1 and H2S2V2.  The distance is calculated as sqrt((H2-H1)^2+(S2-S1)^2+(V2-V1)^2).
0

Author Commented:
Unfortunately the vector distance (3d space) is not the same as perceptual color difference for the human eye. I was hoping for an algorithm to mimick how the eye would determine that the two colors are the same.

Thanks for all the responses so far
0

Commented:
To get an idea of the complexity of your problem see this article:

You could use the formula here and assume they know what they are talking about:
http://www.ee.columbia.edu/ln/dvmm/researchProjects/MultimediaIndexing/VisualSEEk/acmmm96/node8.html
0

Commented:
Since that's hard to read, you could get the same result by using
``````distance[i] = pow(array[i].v - color.v, 2)
+ pow(array[i].s*cos(array[i].h) - color.s*cos(color.h), 2)
+ pow(array[i].s*sin(array[i].h) - color.s*sin(color.h), 2)
``````
and finding the smallest
0

Commented:
using pow(x,2) to mean x^2 or x*x
0

Author Commented:
wow, thank you!  I'll give it a try and post back shortly
0

## Featured Post

• 5
• 2
Tackle projects and never again get stuck behind a technical roadblock.