views:

904

answers:

4

Is there a way to compare how close two colors are to each other? If to say both of them are blue.
At the moment the way that we compare them is to manually assign each possible color to a color family(red, green, blue...). And then just compare the strings :)
But surely that manual task can be assigned to a neat little algorithm.

+20  A: 

You probably want to convert the colors to an HSL model (Hue, Saturation, Lightness) and then compare the values within thresholds in the order HSL. If the hue is within a tolerance deemed as "close", then check the "closeness" of the saturation, and then the lightness.

Jeff Yates
I think this is a better answer than David's, since without knowing otherwise I'd guess with OP will find a comparison based on HSL will be more useful than one based on RGB.
Adam Bellaire
er... the Op, not with Op....
Adam Bellaire
@Adam Bellaire, can you explain why that might be? I'm not too clear on the differences between RGB and HSL myself
matt b
+1. HSL can be converted from/to RGB rather easily: http://130.113.54.154/~monger/hsl-rgb.html
Michael Stum
@matt: See my comment on David's answer. Basically, I think people naturally consider hue to be more important than saturation or lightness when comparing colors. RGB mixes these attributes in the representation, making it hard to compare numerically. HSL separates them, making it easier.
Adam Bellaire
Nice idea; but there are some corner cases you'd want to deal with, for instance, if the saturation is very low the hue doesn't matter much. If the lightness is very low, saturation probably isn't that important.
Dickon Reed
@Dickon: Good point. I think with this kind of algorithm, there are always going to be those special cases that don't quite fit the model.
Jeff Yates
A: 

Depending on what you mean by close, you can compare the RGB hex strings with your favorite number comparison algorithms. Some things to look at would be the hue, saturation, value, etc. I don't remember how those different attributes affect the hex values, but playing around with any color picker that gives you these sliders, and will display the hex should quickly show how things change.

cdeszaq
+7  A: 

I'm not sure of any algorithms, you may want to consider converting RGB (Red, Green, Blue) values in to HSB (Hue, Saturation, Brightness).

Hue is essentially "color", so you can compare simply on how close the Hue values are.

See http://en.wikipedia.org/wiki/HSV_color_space

nicholaides
A: 

My first idea is to treat the RGB space as three-dimensional (cartesian) space, and calculate the distance accordingly as

(sqrt (+ (square diff-red)
         (square diff-green)
         (square diff-blue)))

edit: The usefulness of this depends on what you want to do with it. Just being darker would be interpreted as a different colour this way, I don't know whether you want that.

Svante