How to determine if color is close to other color

2019-09-09 13:06发布

问题:

I am creating kind of color tool and this tool should tell me if color is close to other 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 ColorsAreClose() Function Look?

回答1:

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.



回答2:

A simple way, measeure 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 wit hthe maximum deviation you want to consider close.



回答3:

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.



回答4:

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;
}


回答5:

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.



回答6:

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