> 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 SSIM from scikit-image

Python programs often calculate the structural similarity (SSIM) of two
images with
[`skimage.metrics.structural_similarity`](https://scikit-image.org/docs/stable/api/skimage.metrics.html#skimage.metrics.structural_similarity)
of scikit-image. `ssim` of `anyformat-image` calculates the same metric:

- Its score is the score of `structural_similarity` with these settings, on
  the luma of the two images, within 1e-6:

  ```python
  structural_similarity(
      a,
      b,
      gaussian_weights=True,
      sigma=1.5,
      use_sample_covariance=False,
      data_range=255,
  )
  ```

  The default settings of scikit-image give different scores. See
  [Settings](#settings).
- It decodes PNG files itself. You do not need Pillow, NumPy, or SciPy.
- It releases the GIL and uses all CPU cores. On two decoded 1920 × 1080
  images, it was about 17 times faster than scikit-image with the same
  settings. With two PNG files, it was about 8 times faster than Pillow and
  scikit-image. See [Performance](#performance).

See [`ssim`](https://anyformat.swc.rs/api/image.md#ssim) in the image API reference for the full
API. To migrate from ssim.js in Node.js, read
[Migrate from ssim.js](https://anyformat.swc.rs/guide/node/migrate-from-ssim-js.md).

Install the package:

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

## Compare two PNG files

With Pillow and scikit-image:

```python
import numpy as np
from PIL import Image
from skimage.metrics import structural_similarity

a = np.asarray(Image.open("expected.png").convert("L"))
b = np.asarray(Image.open("actual.png").convert("L"))

score = structural_similarity(a, b)
assert score >= 0.98, score
```

With `anyformat-image`:

```python
from pathlib import Path

import anyformat_image

result = anyformat_image.ssim(
    Path("expected.png").read_bytes(),
    Path("actual.png").read_bytes(),
)
assert result.ssim >= 0.98, result.ssim
```

The two programs do not give the same score, because the first program
uses the default settings of scikit-image. Before you keep a threshold such
as `0.98`, read [Settings](#settings).

## Compare NumPy arrays

`ssim` accepts encoded files and `RawImage` objects. It does not accept a
NumPy array directly: it reads `bytes` and other buffers as an encoded file.
Convert an array to an opaque RGBA image first:

```python
import numpy as np

from anyformat_image import RawImage, ssim


def to_raw(pixels: np.ndarray) -> RawImage:
    """A uint8 array with the shape (height, width) or (height, width, 3)."""
    height, width = pixels.shape[:2]
    rgba = np.empty((height, width, 4), dtype=np.uint8)
    rgba[..., :3] = pixels[..., None] if pixels.ndim == 2 else pixels
    rgba[..., 3] = 255
    return RawImage(width, height, rgba)


result = ssim(to_raw(a), to_raw(b))
```

For a gray image, R, G, and B have the same value, so the luma is that
value. Thus for two gray `uint8` arrays, `ssim(to_raw(a), to_raw(b)).ssim`
is the score of `structural_similarity(a, b, gaussian_weights=True,
sigma=1.5, use_sample_covariance=False, data_range=255)` within 1e-6.

`ssim` accepts only 8-bit samples. Convert a floating-point image from 0 to
1 with `(np.clip(x, 0, 1) * 255).round().astype(np.uint8)`. The rounding to
8 bits can change the score a little.

## Settings

The default settings of `structural_similarity` are not the settings of
`ssim`:

| Setting                       | scikit-image default                         | `ssim`                                   |
| ----------------------------- | -------------------------------------------- | ---------------------------------------- |
| Window                        | 7 × 7, uniform (`win_size=7`)                | 11 × 11, Gaussian with sigma 1.5         |
| Covariance                    | Sample covariance                            | Population covariance                    |
| Data range                    | 255 for `uint8`; required for floating-point | 255                                      |
| `K1`, `K2`                    | 0.01, 0.03                                   | 0.01, 0.03                               |
| Color images (`channel_axis`) | The mean of the SSIM of each channel         | The SSIM of the luma                     |
| Mean                          | Over the pixels 3 or more from each edge     | Over the pixels 5 or more from each edge |

These scores were measured with scikit-image 0.26.0 and Pillow 13.0.0. The
inputs were a 512 × 512 photograph and a 1920 × 1080 enlargement of it, each
with four changed copies: JPEG at quality 30 and 80, Gaussian noise with
sigma 10, and a Gaussian blur with radius 1. The columns of scikit-image
used these inputs and settings:

- **Gray, `ssim` settings:** `Image.convert("L")`, with the settings of
  `ssim`.
- **Gray, defaults:** `Image.convert("L")`, with the default settings.
- **RGB, defaults:** the RGB array, with `channel_axis=2`.

| Image, change        | `ssim` | Gray, `ssim` settings | Gray, defaults | RGB, defaults |
| -------------------- | ------ | --------------------- | -------------- | ------------- |
| 512 × 512, JPEG 30   | 0.9311 | 0.9307                | 0.9371         | 0.8976        |
| 512 × 512, JPEG 80   | 0.9713 | 0.9710                | 0.9742         | 0.9458        |
| 512 × 512, noise     | 0.7451 | 0.7443                | 0.7551         | 0.6501        |
| 512 × 512, blur      | 0.9378 | 0.9368                | 0.9424         | 0.9357        |
| 1920 × 1080, JPEG 30 | 0.9665 | 0.9660                | 0.9659         | 0.9356        |
| 1920 × 1080, JPEG 80 | 0.9911 | 0.9908                | 0.9913         | 0.9719        |
| 1920 × 1080, noise   | 0.6564 | 0.6554                | 0.6653         | 0.5259        |
| 1920 × 1080, blur    | 0.9929 | 0.9924                | 0.9927         | 0.9920        |

Pillow rounds the gray value of `convert("L")` to an integer. `ssim` does
not round the luma, so the scores differ a little also with the same
settings. The scores of the defaults can be higher or lower than the scores
of `ssim`, so a threshold from scikit-image can pass or fail other images.
Do these steps:

1. Calculate the scores of some image pairs with both packages.
2. Set new thresholds from the scores of `ssim`.

## API mapping

| scikit-image                                          | `anyformat-image`                                                            |
| ----------------------------------------------------- | ---------------------------------------------------------------------------- |
| `structural_similarity(a, b, ...)`                    | `ssim(a, b).ssim`                                                            |
| `structural_similarity(..., full=True)`               | `ssim(a, b, map=True)`; see [The map](#the-map)                              |
| `gradient=True`                                       | No replacement                                                               |
| `win_size`, `gaussian_weights`, `sigma`               | No options. The window is Gaussian, 11 × 11, with sigma 1.5                  |
| `use_sample_covariance`                               | No option. The value is `False`                                              |
| `data_range`                                          | No option. The inputs are 8-bit, and the data range is 255                   |
| `K1`, `K2`                                            | No options. The values are 0.01 and 0.03                                     |
| `channel_axis`                                        | No option; see [Color and alpha](#color-and-alpha)                           |
| `Image.open(path)` and `np.asarray`                   | Give the encoded PNG file, or decode it with `decode` or `decode_file`       |
| `skimage.color.rgb2gray`                              | No call. `ssim` calculates the luma; see [Color and alpha](#color-and-alpha) |
| `ValueError` for images of different sizes            | `ImageSizeMismatchError`, a subclass of `ValueError`                         |
| `ValueError` when `win_size` is larger than the image | `ValueError` when a side is less than 11 pixels                              |

`ssim` also accepts encoded files and decodes the two files at the same
time. Only PNG files can be decoded today. To compare files of other
formats, decode them with Pillow and use `to_raw` from
[Compare NumPy arrays](#compare-numpy-arrays).

## Color and alpha

- **Luma.** `ssim` calculates the luma of each pixel with the ITU-R BT.601
  weights, `0.299 R + 0.587 G + 0.114 B`. These are the weights of Pillow
  `convert("L")`. `skimage.color.rgb2gray` uses other weights,
  `0.2125 R + 0.7154 G + 0.0721 B`, so it gives other scores, mostly when
  the changes are in color, for example noise in each channel.
- **Color.** With `channel_axis`, scikit-image calculates the SSIM of each
  channel and returns the mean. `ssim` does not compare colors: two images
  with the same luma give 1. To find changes in color, use
  [`compare_images`](https://anyformat.swc.rs/api/image.md#compareimages).
- **Alpha.** `ssim` composites each pixel over white before it calculates
  the luma, so a transparent pixel and an opaque white pixel have the same
  luma. scikit-image has no concept of alpha. With `channel_axis` on an RGBA
  array, it compares the alpha channel as a fourth color channel.

## The map

With `full=True`, scikit-image returns the SSIM map as a floating-point
array of the size of the image. With `map=True`, `ssim` returns the map as a
`RawImage` of the same size:

- Each pixel has `round(clamp(ssim, 0, 1) * 255)` in R, G, and B, and 255 in
  A. Thus the values are rounded to steps of 1/255, and negative values
  become 0.
- The map includes the pixels near the edges. At the edges, the filter
  reflects the image, as scikit-image does. The values are the values of
  the map of scikit-image, clamped to 0..1 and rounded.

To get the map as a NumPy array of numbers from 0 to 1:

```python
result = ssim(a, b, map=True)
m = result.map
values = np.frombuffer(m.data, dtype=np.uint8).reshape(m.height, m.width, 4)[..., 0] / 255
```

The map is a valid input of `encode`, so you can write it to a PNG file:

```python
Path("ssim-map.png").write_bytes(anyformat_image.encode(m, anyformat_image.PngEncodeOptions()))
```

## Performance

A measurement on one x86_64 Linux computer (Intel Core i7-13700F, 24
threads) with Python 3.12, scikit-image 0.26.0, NumPy 2.5.5, SciPy 1.18.1,
and Pillow 13.0.0. The inputs were the 1920 × 1080 photograph of
[Settings](#settings) and its copy at JPEG quality 30. Each value is the
median of several calls. "One thread" is the time with
`RAYON_NUM_THREADS=1`.

Time to calculate the SSIM of two 1920 × 1080 images

Shorter is faster. Each operation has its own scale.

- anyformat-image
- scikit-image and Pillow

Gray uint8 arrays

scikit-image, defaults88.5 ms

scikit-image, ssim settings117.0 ms

anyformat-image, with to_raw22.1 ms

anyformat-image, with to_raw, one thread80.5 ms

Decoded RGBA images

scikit-image, ssim settings, on the luma132.0 ms

anyformat-image7.7 ms

anyformat-image, one thread67.0 ms

Decode two PNG files

Pillow convert("L"), scikit-image, defaults166.0 ms

Pillow convert("L"), scikit-image, ssim settings190.0 ms

anyformat-image23.7 ms

anyformat-image, one thread93.0 ms

Show the data as a table

| Operation | Package | Time |
| --- | --- | --- |
| Gray uint8 arrays | scikit-image, defaults | 88.5 ms |
| Gray uint8 arrays | scikit-image, ssim settings | 117.0 ms |
| Gray uint8 arrays | anyformat-image, with to_raw | 22.1 ms |
| Gray uint8 arrays | anyformat-image, with to_raw, one thread | 80.5 ms |
| Decoded RGBA images | scikit-image, ssim settings, on the luma | 132.0 ms |
| Decoded RGBA images | anyformat-image | 7.7 ms |
| Decoded RGBA images | anyformat-image, one thread | 67.0 ms |
| Decode two PNG files | Pillow convert("L"), scikit-image, defaults | 166.0 ms |
| Decode two PNG files | Pillow convert("L"), scikit-image, ssim settings | 190.0 ms |
| Decode two PNG files | anyformat-image | 23.7 ms |
| Decode two PNG files | anyformat-image, one thread | 93.0 ms |


scikit-image uses one thread. In the first group, `to_raw` copies the gray
array into an RGBA array, and this copy takes most of the time. When you
have the PNG files, give the files to `ssim`.
