0

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?

Community
  • 1
  • 1
Joey Morani
  • 25,431
  • 32
  • 84
  • 131
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Jan 08 '13 at 02:49
  • Sorry, my bad. At least I know now. Pretty sure I've done it in the past as well so oops! – Joey Morani Jan 08 '13 at 02:55
  • 1
    @JoeyMorani: thanks for letting me know. I think I've got them all now. – John Saunders Jan 08 '13 at 03:17

3 Answers3

4

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.

Andrew Marshall
  • 1,469
  • 13
  • 14
2

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.

Community
  • 1
  • 1
1

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

Eli Algranti
  • 8,707
  • 2
  • 42
  • 50