pixelmatch
pixelmatch-py is a fast, pure-Python library for pixel-level image comparison, originally designed for comparing screenshots in tests. It provides accurate anti-aliased pixel detection and perceptual color difference metrics. This library is a Python port of the popular JavaScript `mapbox/pixelmatch` library and currently supports Python versions 3.10 and newer, with a stable release cadence.
Warnings
- breaking `pixelmatch.contrib.PIL.pixelmatch` now uses a fast path for byte-identical images. When an `output` image is provided and `diff_mask=False`, grayscale diff output values can differ slightly (typically up to +/-1 per channel due to PIL rounding) compared to previous versions. This primarily affects the exact pixel values of the generated diff image, not the mismatch count.
- breaking Support for older Python versions (3.7-3.9) has been dropped.
- gotcha The primary `pixelmatch` function (for raw image data) and the PIL-contributed `pixelmatch` function expect input images to have identical dimensions. If dimensions differ, an error will be raised or unexpected results may occur.
- gotcha For raw image data comparison, the `pixelmatch` function expects RGBA image data (e.g., a byte array where pixels are represented as [R, G, B, A, R, G, B, A, ...]). Incorrect data format will lead to wrong comparisons or errors.
- gotcha The `pixelmatch` (pure Python) package is significantly slower than its C++-bound alternative, `pybind11-pixelmatch`, especially for large images or frequent comparisons. While `pixelmatch` is a pure Python port, `pybind11-pixelmatch` offers superior performance for performance-critical applications.
Install
-
pip install pixelmatch -
pip install pixelmatch pillow
Imports
- pixelmatch
from pixelmatch import pixelmatch
- pixelmatch
from pixelmatch.contrib.PIL import pixelmatch
Quickstart
from PIL import Image
from pixelmatch.contrib.PIL import pixelmatch
import io
def create_dummy_image(width, height, color):
img = Image.new('RGBA', (width, height), color)
return img
# Create two identical images
img1 = create_dummy_image(100, 100, (255, 0, 0, 255)) # Red image
img2 = create_dummy_image(100, 100, (255, 0, 0, 255)) # Red image
# Make a slight difference in img2
img2.putpixel((10, 10), (0, 0, 255, 255)) # Blue pixel at (10,10)
img_diff = Image.new('RGBA', img1.size)
mismatch = pixelmatch(img1, img2, img_diff, threshold=0.1, includeAA=True)
print(f"Number of mismatched pixels: {mismatch}")
# Save the diff image (optional, for visualization)
# To run this, you'd need actual file paths or use BytesIO
# with open('diff.png', 'wb') as f:
# img_diff.save(f, format='PNG')
# print("Diff image saved as diff.png")