How to compare two images pixel by pixel

The task might seem trivial, but I can assure you it's not. Smile Every image manipulation program handles file formats a little differently, so if you take an image file (let's assume it uses a lossless format, eg. PNG) and simply save/export it with two different programs, but using the same (lossless) format, the two resulting files will be most probably different in size (and obviously in content too). The question is: how do you know whether the two images are the same or not? The size of the two files can differ for a number of reasons and not just because of the difference of the image data. Eg. modern file formats allow a lot of metadata to be stored with the image. Some file formats allow the use of more than one compression algorithms (eg. TIFF files can use a number of -lossless- compression algorithms).

A practical use for a pixel-by-pixel comparison of two image files might be to check whether an image manipulation program uses lossless operations (eg. rotation).

ImageMagick's compare command gives all the tools you need to compare two images. Among the many possible comparison algorithms "AE" (Absolute Error count) is the one we need for pixel-by-pixel comparison:
compare -verbose -metric AE image1.png image2.png null:

If the two images are perfectly the same, you'll get zero channel distortion:
image1.png PNG 720x1280 720x1280+0+0 8-bit DirectClass 327KB 0.110u 0:00.130
image2.png PNG 720x1280 720x1280+0+0 8-bit DirectClass 327KB 0.130u 0:00.129
Image: image1.png
  Channel distortion: AE
    red: 0
    green: 0
    blue: 0
    all: 0
image1.png=> PNG 720x1280 720x1280+0+0 8-bit DirectClass 0.330u 0:00.350

If the images are different, you'll see the number of different pixels in the "all:" line:
image1.png PNG 720x1280 720x1280+0+0 8-bit DirectClass 327KB 0.110u 0:00.130
image2.png PNG 720x1280 720x1280+0+0 8-bit DirectClass 319KB 0.130u 0:00.119
Image: image1.png
  Channel distortion: AE
    red: 1
    green: 1
    blue: 1
    all: 1
image1.png=> PNG 720x1280 720x1280+0+0 8-bit DirectClass 0.320u 0:00.330

And this is just the tip of the iceberg. ImageMagick's compare command has a lot more to offer. Check out the link of this post for a detailed description.

P.S.: the latter output was achieved by manually altering a single pixel in image1.png (using GIMP) and saving it as image2.png.