How to determine if a color is close to another color

11.5k Views Asked by At

I am creating a kind of color tool and this tool should tell me if color is close to another color, For example:

Color[] colors = new colors[] { Color.FromArgb(0,0,255), Color.FromArgb(0,109,251)};
//colors[0] IS BLUE
//colors[1] IS BRIGHTER BLUE (#006DFB)
bool TheyClose = ColorsAreClose(colors[0],colors[1]); //TRUE BLUE IS CLOSE
//TheyColse Should Be = TURE

How should a ColorsAreClose() function Look?

6

There are 6 best solutions below

0
On BEST ANSWER

How about something like this?

bool ColorsAreClose(Color a, Color z, int threshold = 50)
{
    int r = (int)a.R - z.R,
        g = (int)a.G - z.G,
        b = (int)a.B - z.B;
    return (r*r + g*g + b*b) <= threshold*threshold;
}

(I just guessed at the default threshold, but you should set it to what you want.)

Basically this just computes, on average, whether the three color channels are close enough between the two colors.

1
On

A simple way, measure RGB distance:

public bool ColorsAreClose(Color[] colors)
{

    var rDist = Math.Abs(colors[0].R - colors[1].R);
    var gDist = Math.Abs(colors[0].G - colors[1].G);
    var bDist = Math.Abs(colors[0].B - colors[1].B);

    if(rDist + gDist + bDist > Threshold)
        return false;

    return true;

}

Threshold is a constant with the maximum deviation you want to consider close.

0
On

This is somewhat subjective and not scientific, I used the following procedure on a project once.

public bool IsMatch(Color colorA, Color colorB)
{
    return IsMatch(colorA.Red, colorB.Red)
        && IsMatch(colorA.Green, colorB.Green)
        && IsMatch(colorA.Blue, colorB.Blue);
}

public bool IsMatch(double colorA, double colorB)
{
    var difference = colorA - colorB;
    return -5 < difference
        || difference < 5;
}
0
On

If talking just about hue you could compare the difference in RGB values separately and if the total difference is under a set amount set by you then you could call them close.

0
On

You can start with:

double delta = Math.Abs(c1.GetHue() - c2.GetHue());
if(delta > 180)
  delta = 360 - delta;
return delta <= threshold 

For more info about the hue see: http://en.wikipedia.org/wiki/Hue

0
On

You can calculate the 3-D color space distance as

Math.Sqrt(Math.Pow(c1.R-c2.R,2)+Math.Pow(c1.G-c2.g,2)+Math.Pow(c1.B-c2.b,2))); 

or you can calculate the hue difference as

Math.Abs(c1.GetHue() - c2.GetHue());

A more thorough discussion can be found here.