For AI agents: the complete documentation index is available at https://anyformat.swc.rs/llms.txt, the full documentation bundle is available at https://anyformat.swc.rs/llms-full.txt, and this page is available as Markdown at https://anyformat.swc.rs/guide/python/migrate-from-pixelmatch-py.md.

Migrate from pixelmatch-py

Python visual regression tests often use pixelmatch-py (pixelmatch on PyPI) to compare screenshots, and Pillow or pypng to read and write the PNG files. pixelmatch-py is written in pure Python, so a comparison of two 1920 × 1080 screenshots takes more than a second. It also holds the GIL, so other threads cannot compare images at the same time. anyformat-image replaces it:

  • The diff count and the diff image are the same as the results of pixelmatch-py 0.4.0 when you set algorithm="pixelmatch6". See Select the algorithm.
  • One call can decode two files, compare them, and encode the diff image. In the measurement below, this took about 30 ms. Pillow and pixelmatch-py took about 1.7 s.
  • compare_images releases the GIL and uses all CPU cores. Thread pools and asyncio.to_thread can run several comparisons in parallel.
  • The package has no runtime dependencies. You do not need Pillow or NumPy to read and write PNG files.

See the image API reference for the full API. To migrate from pngjs and pixelmatch in Node.js, read Migrate from pngjs and pixelmatch.

Install the package:

pip install anyformat-image

Compare two PNG files

With Pillow and pixelmatch-py:

from PIL import Image
from pixelmatch.contrib.PIL import pixelmatch

img_a = Image.open("expected.png")
img_b = Image.open("actual.png")
img_diff = Image.new("RGBA", img_a.size)

mismatch = pixelmatch(img_a, img_b, img_diff, threshold=0.1)

img_diff.save("diff.png")

With anyformat-image:

from pathlib import Path

import anyformat_image

result = anyformat_image.compare_images(
    Path("expected.png").read_bytes(),
    Path("actual.png").read_bytes(),
    algorithm="pixelmatch6",
    threshold=0.1,
    diff=anyformat_image.PngEncodeOptions(),
)
mismatch = result.diff_pixels

if result.diff_encoded is not None:
    Path("diff.png").write_bytes(result.diff_encoded)

compare_images decodes the files itself. When the program also needs the pixels of the two files, for example to draw a composite of the two images and the diff, add decoded=True. The result then has the decoded pixels in decoded_a and decoded_b, so the program does not decode the files again. See Decoded inputs.

Compare images in memory

To compare images that are already in memory, wrap the pixels in a RawImage. The pixels must be 8-bit RGBA, row by row, with width * height * 4 bytes. The raw API of pixelmatch-py uses the same layout, so you can give the same bytes:

import anyformat_image
from anyformat_image import RawImage

# pixelmatch-py:
#   output = bytearray(len(img1))
#   mismatch = pixelmatch(img1, img2, width, height, output, threshold=0.1)

result = anyformat_image.compare_images(
    RawImage(width, height, img1),
    RawImage(width, height, img2),
    algorithm="pixelmatch6",
    threshold=0.1,
    diff="raw",
)
mismatch = result.diff_pixels
output = result.diff_image.data

RawImage uses bytes without a copy and copies other buffers once, for example a bytearray or a NumPy uint8 array with the shape (height, width, 4). It does not accept a list of integers. Convert a list with bytes(img1).

To compare Pillow images, convert them to RGBA first. To make a Pillow image from the diff image, use Image.frombytes:

from PIL import Image

import anyformat_image
from anyformat_image import RawImage


def to_raw(img: Image.Image) -> RawImage:
    return RawImage(img.width, img.height, img.convert("RGBA").tobytes())


result = anyformat_image.compare_images(
    to_raw(img_a), to_raw(img_b), algorithm="pixelmatch6", diff="raw"
)
diff = result.diff_image
img_diff = Image.frombytes("RGBA", (diff.width, diff.height), diff.data)

Select the algorithm

pixelmatch-py 0.4.0 is a port of pixelmatch 5 for JavaScript. It uses the YIQ color metric and blends semi-transparent pixels with white. algorithm="pixelmatch6" gives the same results as pixelmatch 6.0.0 and 5.3.0, which use the same metric, so your thresholds and baselines stay valid.

The default algorithm, "pixelmatch8", uses the OKLab HyAB metric of pixelmatch 8. Its counts are different for the same threshold. Use it only when you can tune the thresholds again and make new baselines. See Algorithms.

API mapping

pixelmatch-pyanyformat-image
pixelmatch(img1, img2, width, height)compare_images(RawImage(width, height, img1), ...).diff_pixels
pixelmatch(img1, img2, width, height, output)compare_images(..., diff="raw").diff_image.data
contrib.PIL.pixelmatch(img_a, img_b)compare_images(to_raw(img_a), to_raw(img_b)).diff_pixels
contrib.PIL.pixelmatch(img_a, img_b, img_diff)compare_images(..., diff="raw") and Image.frombytes
Image.open twice, pixelmatch, img_diff.savecompare_images(bytes_a, bytes_b, diff=PngEncodeOptions())
threshold, alpha, aa_color, diff_colorThe same names
diff_maskdiff_mask
includeAAinclude_aa
fail_fast=TrueNo replacement. Check diff_pixels > 0
ValueError for images of different sizesImageSizeMismatchError, a subclass of ValueError
Image.open(path).convert("RGBA").tobytes()decode_file(path).data (see Decoding)
png.Reader(bytes=data).asRGBA8()decode(data). The result has width, height, and data
png.Writer(width, height, alpha=True).write(f, rows)encode(RawImage(width, height, data), PngEncodeOptions())
png.Writer(width, height, alpha=False)PngEncodeOptions(color_type="rgb")
png.Writer(width, height, greyscale=True)PngEncodeOptions(color_type="gray"). The input is RGBA, not gray samples

The options have the same defaults as in pixelmatch-py. compare_images checks them more strictly: threshold and alpha must be numbers from 0 to 1, and a color must be a sequence of three integers from 0 to 255. See Compare options.

compare_images also has features that pixelmatch-py does not have:

  • diff_bounds: the smallest rectangle that contains all different pixels.
  • antialiased_pixels: the number of different pixels that the comparison ignored as anti-aliasing.
  • window_size: the largest number of different pixels in any N × N window, in window_diff_pixels.
  • ignore_mask: pixels that the comparison skips, for example a clock or an ad in a screenshot. See Ignore mask.
  • diff_color_alt: a second color for pixels that are darker in the second image.

Differences from pixelmatch-py

  • Identical images with contrib.PIL. When the two images are identical, contrib.PIL.pixelmatch 0.4.0 draws the gray diff image with Pillow. Its bytes can differ by 1 or 2 from the bytes of the pixelmatch algorithm. compare_images always uses the pixelmatch algorithm, as the raw pixelmatch.pixelmatch function does. The diff count is 0 in both cases.
  • diff_mask with an output that is not empty. pixelmatch-py writes only the different pixels when diff_mask is set, and keeps the other bytes of the output. diff_image is transparent at these pixels, so a program that fills the output first, for example with a copy of the first image, must draw the diff image over that copy itself.
  • Return value. compare_images returns a CompareResult, not a number, and it makes the diff image. It does not write into an output of the caller.

Decoding

compare_images, decode, and decode_file decode a PNG file in other ways than Pillow in these cases:

  • EXIF orientation. decode applies the orientation of an eXIf chunk by default, as browsers do, so the width and the height can change. Pillow ignores it in Image.open. To get the pixels of Pillow, pass orientation="ignore" to decode, or decode=DecodeOptions(orientation="ignore") to compare_images.
  • 16-bit samples and gray files with a tRNS chunk. Pillow converts them in other ways. See Raw images.

When you compare two PNG files that were made by the same program, these cases usually do not apply. Only PNG files can be decoded today. To compare files of other formats, decode them with Pillow and give the pixels as a RawImage.

Performance

A measurement on one x86_64 Linux computer (Intel Core i7-13700F, 24 threads) with Python 3.12, pixelmatch-py 0.4.0, Pillow 13.0.0, and pypng 0.20220715.0. The inputs were one synthetic 1920 × 1080 screenshot with text and rectangles, and a changed copy with 1933 different pixels. Each value is the median of several calls. A range shows the medians of three runs when they were not close.

Time of each operation with one 1920 × 1080 screenshot

Shorter is faster. Each operation has its own scale.

Decode PNG to RGBA
Encode PNG
Compare raw images with a diff image
Decode two files, compare, encode the diff
Show the data as a table
OperationPackageTime
Decode PNG to RGBApypng750 ms
Decode PNG to RGBAPillow18 ms
Decode PNG to RGBAanyformat-image6 ms
Encode PNGpypng31 ms
Encode PNGPillow56 ms
Encode PNGanyformat-image17 ms
Compare raw images with a diff imagepixelmatch-py1610 ms
Compare raw images with a diff imageanyformat-image1.0–2.3 ms
Compare raw images with a diff imageanyformat-image, one thread3.2 ms
Decode two files, compare, encode the diffpixelmatch-py (Pillow, contrib.PIL)1690 ms
Decode two files, compare, encode the diffanyformat-image25–35 ms
Decode two files, compare, encode the diffanyformat-image, one thread37 ms

The diff counts and the diff images were identical. "One thread" is the time with RAYON_NUM_THREADS=1. The encoded files had different sizes: 320 KiB with pypng, 408 KiB with Pillow, and 387 KiB with anyformat-image (compression="balanced"). Measure with your own images if the file size matters. See PNG options.