How to subtract one bitmap from another in C#/.NET?

Lasse V. Karlsen picture Lasse V. Karlsen · Dec 29, 2008 · Viewed 8.2k times · Source

I have two bitmaps, produced by different variations of an algorithm. I'd like to create a third bitmap by subtracting one from the other to show the differences.

How can this be done in .NET? I've looked over the Graphics class and all its options, including the ImageAttributes class, and I have a hunch it involves the color matrix or remap tables functionality.

Does anyone have a link to some example code, or can point me in the right direction? A google search doesn't reveal much, unless my google-fu is failing me today.

Answer

adzm picture adzm · Dec 29, 2008

The real question is, what differences do you want to show? If you just need to operate on RGB color values, the best bet in my opinion is to just scan through both bitmaps and compare the Color values using GetPixel, and use SetPixel to generate your 'difference' bitmap. Perhaps you simply want to subtract the values and use those as the new Color value for the third bitmap. Or perhaps you want to calculate out the luminosity and use that. Even better, if you have three metrics for comparison, assign each one to the R G and B components of the color. I've used this approach for fractal colorization before.

There are other approaches, but with this one you are limited only to your imagination. It may not be the fastest approach, but it does not sound like performance is necessary for this scenario.