> 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.

# Migrate from pixelmatch-py

Python visual regression tests often use
[pixelmatch-py](https://github.com/whtsky/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](#select-the-algorithm).
- One call can decode two files, compare them, and encode the diff image.
  In the [measurement below](#performance), 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](https://anyformat.swc.rs/api/image.md) for the full API. To migrate
from pngjs and pixelmatch in Node.js, read
[Migrate from pngjs and pixelmatch](https://anyformat.swc.rs/guide/node/migrate-from-pngjs-and-pixelmatch.md).

Install the package:

```sh
pip install anyformat-image
```

## Compare two PNG files

With Pillow and pixelmatch-py:

```python
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`:

```python
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](https://anyformat.swc.rs/api/image.md#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:

```python
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`:

```python
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](https://anyformat.swc.rs/api/image.md#algorithms).

## API mapping

| pixelmatch-py                                          | `anyformat-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.save`      | `compare_images(bytes_a, bytes_b, diff=PngEncodeOptions())`                |
| `threshold`, `alpha`, `aa_color`, `diff_color`         | The same names                                                             |
| `diff_mask`                                            | `diff_mask`                                                                |
| `includeAA`                                            | `include_aa`                                                               |
| `fail_fast=True`                                       | No replacement. Check `diff_pixels > 0`                                    |
| `ValueError` for images of different sizes             | `ImageSizeMismatchError`, a subclass of `ValueError`                       |
| `Image.open(path).convert("RGBA").tobytes()`           | `decode_file(path).data` (see [Decoding](#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](https://anyformat.swc.rs/api/image.md#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](https://anyformat.swc.rs/api/image.md#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](https://anyformat.swc.rs/api/image.md#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.

- anyformat-image
- pixelmatch-py, Pillow, or pypng

Decode PNG to RGBA

pypng750 ms

Pillow18 ms

anyformat-image6 ms

Encode PNG

pypng31 ms

Pillow56 ms

anyformat-image17 ms

Compare raw images with a diff image

pixelmatch-py1610 ms

anyformat-image1.0–2.3 ms

anyformat-image, one thread3.2 ms

Decode two files, compare, encode the diff

pixelmatch-py (Pillow, contrib.PIL)1690 ms

anyformat-image25–35 ms

anyformat-image, one thread37 ms

Show the data as a table

| Operation | Package | Time |
| --- | --- | --- |
| Decode PNG to RGBA | pypng | 750 ms |
| Decode PNG to RGBA | Pillow | 18 ms |
| Decode PNG to RGBA | anyformat-image | 6 ms |
| Encode PNG | pypng | 31 ms |
| Encode PNG | Pillow | 56 ms |
| Encode PNG | anyformat-image | 17 ms |
| Compare raw images with a diff image | pixelmatch-py | 1610 ms |
| Compare raw images with a diff image | anyformat-image | 1.0–2.3 ms |
| Compare raw images with a diff image | anyformat-image, one thread | 3.2 ms |
| Decode two files, compare, encode the diff | pixelmatch-py (Pillow, contrib.PIL) | 1690 ms |
| Decode two files, compare, encode the diff | anyformat-image | 25–35 ms |
| Decode two files, compare, encode the diff | anyformat-image, one thread | 37 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](https://anyformat.swc.rs/api/image.md#png-options).
