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.
pip install pixelmatchVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to compare two PIL.Image instances, highlight their differences, and get the count of mismatched pixels. It creates two dummy images, introduces a single pixel difference, and then uses `pixelmatch` to compare them. The `img_diff` object will contain the visual representation of the differences.
Review your test expectations if you rely on precise grayscale values in the diff output when `diff_mask=False` and images are nearly identical. No action needed if you primarily use the mismatch count or `diff_mask=True`.
Ensure your project runs on Python 3.10 or newer.
Always ensure `img1` and `img2` have the same width and height before passing them to `pixelmatch`.
Ensure raw image data is in the expected RGBA byte array format.
For highly performant image comparison, consider using `pybind11-pixelmatch` instead, which is a separate package with a C++ backend. Be aware that its API might differ slightly.
Ensure the library is installed using pip: `pip install pixelmatch` (or `pip install pixelmatch pillow` if using PIL integration).
Before passing images to `pixelmatch`, ensure `img1` and `img2` have been resized or cropped to matching dimensions. For PIL images, you can use `img.resize()` or `img.crop()` to standardize their sizes.
Convert your raw image data into the RGBA byte array format before passing it to the `pixelmatch` function. If you are working with PIL images, use `pixelmatch.contrib.PIL.pixelmatch` instead, which directly accepts `PIL.Image` objects.
Convert the images to a `numpy.ndarray` with `dtype=np.uint8` and shape `(height, width, 3)` (RGB) or `(height, width, 4)` (RGBA) before passing them to `pixelmatch`.
Import and call the correct function: `from pixelmatch import pixelmatch` then `pixelmatch(img1, img2, ...)`.