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}")
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
| Metric | What it measures | Better is |
|---|---|---|
mae | the mean absolute difference, in levels (0 to 255) | lower |
mse | the mean squared difference; large errors count much more | lower |
psnr | the peak signal to noise ratio in decibels, made from the MSE | higher |
ssim | structural similarity: compares local luminance, contrast and structure, 1 for identical | higher, 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 error | stb.mae(a, b) |
|---|---|
| Mean squared error | stb.mse(a, b) |
| Peak signal to noise | stb.psnr(a, b) |
| Structural similarity | stb.ssim(a, b) |
| Where they differ | stb.ssim_map(a, b), a NumPy array |