Skip to main content

Metrics

How different are two pictures? A person looks and says "about the same". A program needs a number, to test an encoder, to pick a JPEG quality, or to check that a refactor did not change the output. libstb has four.

import libstb as stb

original = stb.Image.open("chelsea.png")

# Three ways to damage a picture.
copies = {
"jpeg quality 90": stb.Image.decode(original.to_jpg(quality=90)),
"jpeg quality 20": stb.Image.decode(original.to_jpg(quality=20)),
"gaussian blur 2": stb.gaussian_blur(original, 2.0),
}

print("copy: MAE, MSE, PSNR, SSIM")
for name, copy in copies.items():
mae = stb.mae(original, copy) # the mean absolute difference, in levels
mse = stb.mse(original, copy) # the mean squared difference
psnr = stb.psnr(original, copy) # the peak signal to noise ratio, in dB: higher is closer
ssim = stb.ssim(original, copy) # structural similarity, 1 for identical pictures
print(f"{name}: {mae:.2f}, {mse:.1f}, {psnr:.1f} dB, {ssim:.3f}")
Output
copy: MAE, MSE, PSNR, SSIM
jpeg quality 90: 1.99, 8.0, 39.1 dB, 0.969
jpeg quality 20: 5.27, 51.9, 31.0 dB, 0.845
gaussian blur 2: 5.25, 66.8, 29.9 dB, 0.784

The four numbers​

MetricWhat it measuresBetter is
maethe mean absolute difference, in levels (0 to 255)lower
msethe mean squared difference; large errors count much morelower
psnrthe peak signal to noise ratio in decibels, made from the MSEhigher
ssimstructural similarity: compares local luminance, contrast and structure, 1 for identicalhigher, up to 1

MAE and MSE are plain arithmetic and say how far the numbers moved. PSNR is the MSE on a logarithmic scale and is the usual way to compare codecs. SSIM (Wang et al. 2004, in an 11 by 11 Gaussian window, as scikit-image's) was made to follow what the eye notices, so a blur, which moves few numbers but loses structure, scores worse on SSIM than a JPEG with the same MAE.

The two pictures need the same size and the same channels, and every channel counts, alpha included. PSNR of two identical pictures is infinite, so test with a copy that is a little different.

ssim_map gives the per-pixel SSIM as a NumPy array, so you can see where two pictures differ.

API at a glance​

Mean absolute errorstb.mae(a, b)
Mean squared errorstb.mse(a, b)
Peak signal to noisestb.psnr(a, b)
Structural similaritystb.ssim(a, b)
Where they differstb.ssim_map(a, b), a NumPy array