0

I have a sample image, that is 60x60 in size and I'm trying to locate that sample on a bigger, screenshot image (1920x1080 in size).

My problem is, even though the sample is visible on the screenshot, placed correctly, I'm not able to detect it due to some tiny color differences. As you can see in the below code, pixels are not equal but they are really close in color (about 0.10 in the hue difference). It must be a quality difference between those two then because both bitmaps are in the same format that is Format32bppArgb.

The method I'm using to capture the screen:

private static Bitmap Screenshot(int x, int y, int width, int height)
{
    var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);

    using (var g = Graphics.FromImage(bmp))
    {
        g.CopyFromScreen(x, y, 0, 0, bmp.Size);
        return bmp;
    }
}

This is how I do the comparisons:

private static void Main(string[] args)
{
    // Load a sample
    var sample = (Bitmap)Image.FromFile("sample.png");

    // Capture screen frame
    var screenshot = Screenshot(0, 0, 1920, 1080);

    // Get first pixel in a sample
    var firstPixel = sample.GetPixel(0, 0);

    // Get same pixel in the screenshot
    // sample position first pixel is at 1590x500
    var targetPixel = screenshot.GetPixel(1590, 500);

    // Compare pixels
    var equal = firstPixel.ToArgb() == targetPixel.ToArgb(); // This fails!

    // Get hue levels
    var sourcePixHue = firstPixel.GetHue();
    var targetPixHue = targetPixel.GetHue();

    // Result: a tiny difference
    // sourcePixHue = 12.3076925
    // targetPixHue = 12.4137926
}

My questions:

  • What is the best practice, image format to compare two bitmap pixels so they will be equal?
  • How to properly prepare the sample bitmap to "overcome" the quality/color difference to the screenshot bitmap?
RA.
  • 969
  • 13
  • 36
  • define a range, in which the pixels are allowed to differ from each – fubo Apr 05 '19 at 12:29
  • Well, in the best case scenario I would like having no differences between the sample bitmap and the sample bitmap being placed on the screenshot. In the worst case scenario I would like to somehow "overcome" the differences as much as possible, for example by making the both bitmaps grayscale (but I don't think it would help in this case). – RA. Apr 05 '19 at 12:34
  • I've done a image comparison approach here - maybe is `GetBrightness()` the way to differ in grayscale https://stackoverflow.com/a/35153895/1315444 – fubo Apr 05 '19 at 12:41
  • @DonaldDuck : Can you show how you captured sample.png? My guess is that there could be a slight difference due to a difference in scale and translation of the image, creating linear interpolation with the color of neighboring pixels. – Gilles-Philippe Paillé Apr 05 '19 at 12:48
  • @Gilles-PhilippePaillé `sample.png` is an image made and saved in Photoshop. – RA. Apr 05 '19 at 13:03

0 Answers0