Compare images to find subtle differences in C#

[compare images]

The example Compare images to find differences in C# lets you compare images pixel-by-pixel. Unfortunately it regards the pixels in the images different if they are not exactly the same. That’s fine if the images are full of lines and shapes filled with solid colors, but if you use this method to compare two images that may have been compressed, the program marks pretty much every pixel as different.

This example modifies the previous one’s technique so it only considers two pixels different if they differ by a minimum amount. In the picture above, the program is comparing a bitmap file with a JPG file that has been compressed. The image on the right shows the
pixels that have RGB values that differ by at least 32.

The following code shows the part of the program that determines whether pixels match.

for (int x = 0; x < wid; x++)
    for (int y = 0; y < hgt; y++)
        // Calculate the pixels' difference.
        Color color1 = bm1.GetPixel(x, y);
        Color color2 = bm2.GetPixel(x, y);

        int diff =
            Math.Abs(color1.R - color2.R) +
            Math.Abs(color1.G - color2.G) +
            Math.Abs(color1.B - color2.B);
        if (diff >= min_diff)
            bm3.SetPixel(x, y, ne_color);
            are_identical = false;
            bm3.SetPixel(x, y, eq_color);

The code loops over the pixels in the images. It gets the colors of the corresponding pixels in the two images, and calculates the sum of the absolute values of the differences between their red, green, and blue color components. If that sum is at least the minimum different min_diff, then the program considers the pixels to be different.

By adjusting the minimum difference value, you can make the program show you where the images differ the most.

See the previous example for more details.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in graphics, image processing and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.