比较具有像素差异的位图

时间:2019-04-05 12:18:40

标签: c# image bitmap pixel

我有一个样本图片,大小为60x60,我正在尝试将该样本定位在更大的屏幕截图图片(大小为1920x1080)上。

我的问题是,即使该示例在屏幕截图上可见,但放置正确,由于一些微小的颜色差异,我仍无法检测到它。如您在下面的代码中看到的,像素不相等,但它们的颜色确实很接近(色相差约为0.10)。那么这两者之间必须存在质量差异,因为两个位图的格式都与Format32bppArgb相同。

我用来捕获屏幕的方法:

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

这是我进行比较的方式:

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
}

我的问题:

  • 比较两个位图像素以便它们相等的最佳实践是什么?
  • 如何正确准备示例位图以“克服”屏幕截图位图的质量/颜色差异?

0 个答案:

没有答案