pixelmatch

0.4.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

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.

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")

view raw JSON →