質問

Possible Duplicate:
What is the fastest way I can compare two equal-size bitmaps to determine whether they are identical?

I'm trying to efficiently calculate the differences between two bitmaps and set any matching pixels black. I've tried this:

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

But it turns out that GetPixel and SetPixel are slow so this doesn't really work well enough. Anyone know an alternative (faster) way of doing this?

役に立ちましたか?

解決

This method uses unsafe code, assuming bitmaps are the same size and are 4 bytes per pixel.

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

For a safe method, copy the pixel data to an array buffer for processing using the InteropServices.Marshal.Copy methods.

他のヒント

Raw bitmap data and LockBitmap.

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

Question (missing examples). What is the fastest way I can compare two equal-size bitmaps to determine whether they are identical?

Forget if you turn debug mode off the speed increase. abaut 10x but lockbit is still faster.

Almost sure this has been answered before. You should be using:

Bitmap.LockBits

Also accessing Width and Height (or the other properties with the same info) is also slow so copy them to a local variable if you want to use them in a loop (instead of say the 720 and 1280 in your example.)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top