Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare colors with toleration

Today I am trying to check if one color is similar to another in CSharp from BitMap. This is code, what I am using:

Color blah = screenshot.GetPixel(x, y);
if (blah == Color.Red) {
...

The problem is, that I never get true, because the color has a little bit different shade. Is there any way to compare this colors with some tolerance?

Thanks!


2 Answers

You may check defince a tolarance value and check if their difference is less than that:

Color blah = screenshot.GetPixel(x, y);
    if (Math.Abs(Color.Red.GetHue() - blah.GetHue()) <= tolorance)
    {
        // ...
    }
like image 192
Ashkan Mobayen Khiabani Avatar answered Dec 07 '25 23:12

Ashkan Mobayen Khiabani


Maybe a better solution:

 public bool AreColorsSimilar(Color c1, Color c2, int tolerance)
 {
     return Math.Abs(c1.R - c2.R) < tolerance &&
            Math.Abs(c1.G - c2.G) < tolerance &&
            Math.Abs(c1.B - c2.B) < tolerance;
 }

Source:

  • https://stackoverflow.com/a/7846345/5364144

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!