【问题标题】:Fast way of calculating differences between two bitmaps [duplicate]计算两个位图之间差异的快速方法[重复]
【发布时间】:2013-01-08 02:42:24
【问题描述】:

可能重复:
What is the fastest way I can compare two equal-size bitmaps to determine whether they are identical?

我正在尝试有效地计算两个位图之间的差异并将任何匹配的像素设置为黑色。我试过这个:

for (int x = 0; x < 1280; x++)
{
    for (int y = 0; y < 720; y++)
    {
        if (bitmap.GetPixel(x, y) == bitmap2.GetPixel(x, y))
        {
            bitmap2.SetPixel(x, y, Color.Black);
        }
    }
}

但事实证明,GetPixel 和 SetPixel 很慢,所以这并不能很好地工作。有人知道这样做的替代(更快)方法吗?

【问题讨论】:

  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • 对不起,我的错。至少我现在知道了。很确定我过去也这样做过,哎呀!
  • @JoeyMorani:感谢您告诉我。我想我现在都拥有了。

标签: c# bitmap differentiation


【解决方案1】:

此方法使用不安全代码,假设位图大小相同且每个像素为 4 个字节。

Rectangle bounds = new Rectangle(0,0,bitmapA.Width,bitmapA.Height);
var bmpDataA = bitmapA.LockBits(bounds, ImageLockMode.ReadWrite, bitmapA.PixelFormat);
var bmpDataB = bitmapB.LockBits(bounds, ImageLockMode.ReadWrite, bitmapB.PixelFormat);

const int height = 720;
int npixels = height * bmpDataA.Stride/4;
unsafe {
    int * pPixelsA = (int*)bmpDataA.Scan0.ToPointer();
    int * pPixelsB = (int*)bmpDataB.Scan0.ToPointer();

    for ( int i = 0; i < npixels; ++i ) {
        if (pPixelsA[i] != pPixelsB[i]) {
             pPixelsB[i] = Color.Black.ToArgb();
        }
    }
}
bitmapA.UnlockBits(bmpDataA);
bitmapB.UnlockBits(bmpDataB);

为安全起见,将像素数据复制到数组缓冲区,以便使用InteropServices.Marshal.Copy 方法进行处理。

【讨论】:

    【解决方案2】:

    原始位图数据和 LockBitmap。

    http://www.codeproject.com/Tips/240428/Work-with-bitmap-faster-with-Csharp

    问题(缺少示例)。 What is the fastest way I can compare two equal-size bitmaps to determine whether they are identical?

    忘记是否关闭调试模式会增加速度。大约 10 倍,但 lockbit 仍然更快。

    【讨论】:

      【解决方案3】:

      几乎可以肯定这个问题之前已经回答过了。你应该使用:

      Bitmap.LockBits

      此外,访问 Width 和 Height(或具有相同信息的其他属性)也很慢,因此如果您想在循环中使用它们(而不是示例中的 720 和 1280),请将它们复制到局部变量。

      【讨论】:

        猜你喜欢
        • 2023-03-18
        • 2013-01-16
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-23
        相关资源
        最近更新 更多