2

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!

Samuel Tulach
  • 1,319
  • 13
  • 38

2 Answers2

6

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)
    {
        // ...
    }
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
4

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:

Samuel Tulach
  • 1,319
  • 13
  • 38
  • This is great, except I got an arithmetic exception when I used it. Needed to tweak it (in vb.net) to: Return (Math.Abs(CInt(c1.R) - CInt(c2.R)) < tolerance) AndAlso (Math.Abs(CInt(c1.G) - CInt(c2.G)) < tolerance) AndAlso (Math.Abs(CInt(c1.B) - CInt(c2.B)) < tolerance) – Rob Mar 30 '22 at 19:31