Visualizing the difference of two images as a Heatmap

Pavlos Mavridis

September 2012

Figure 1. Example heatmap generated with this script using the "Spectral" color palette.


One way to compare two images is to use a Heatmap in order to visualize their difference. This is a very common practice in research papers, but surprisingly I could not find any program to perform this operation, so I wrote the following Python script. Feel free to use it and modify it for your own needs.

Python Script

import pylab
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img1 = mpimg.imread('image1.png')
img2 = mpimg.imread('image2.png')

# Calculate the absolute difference on each channel separately
error_r = np.fabs(np.subtract(img2[:,:,0], img1[:,:,0]))
error_g = np.fabs(np.subtract(img2[:,:,1], img1[:,:,1]))
error_b = np.fabs(np.subtract(img2[:,:,2], img1[:,:,2]))

# Calculate the maximum error for each pixel
lum_img = np.maximum(np.maximum(error_r, error_g), error_b)

# Uncomment the next line to turn the colors upside-down
#lum_img = np.negative(lum_img);

imgplot = plt.imshow(lum_img)

# Choose a color palette

(This script requires the NumPy and matplotlib libraries)

Complete list of color palettes

color palettes list