Jhon
Jhon

Reputation: 67

How to determine if a color is close to another color

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?

Upvotes: 3

Views: 12123

Answers (6)

Gusman
Gusman

Reputation: 15151

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.

Upvotes: 6

TaW
TaW

Reputation: 54433

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.

Upvotes: 2

Jashaszun
Jashaszun

Reputation: 9270

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.

Upvotes: 11

romanoza
romanoza

Reputation: 4862

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

Upvotes: 0

RustyH
RustyH

Reputation: 482

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.

Upvotes: 0

jtimperley
jtimperley

Reputation: 2544

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

Upvotes: 0

Related Questions