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-scikit-image.md.

Migrate SSIM from scikit-image

Python programs often calculate the structural similarity (SSIM) of two images with 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:

    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.

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

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

Install the package:

pip install anyformat-image

Compare two PNG files

With Pillow and scikit-image:

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:

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.

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:

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:

Settingscikit-image defaultssim
Window7 × 7, uniform (win_size=7)11 × 11, Gaussian with sigma 1.5
CovarianceSample covariancePopulation covariance
Data range255 for uint8; required for floating-point255
K1, K20.01, 0.030.01, 0.03
Color images (channel_axis)The mean of the SSIM of each channelThe SSIM of the luma
MeanOver the pixels 3 or more from each edgeOver 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, changessimGray, ssim settingsGray, defaultsRGB, defaults
512 × 512, JPEG 300.93110.93070.93710.8976
512 × 512, JPEG 800.97130.97100.97420.9458
512 × 512, noise0.74510.74430.75510.6501
512 × 512, blur0.93780.93680.94240.9357
1920 × 1080, JPEG 300.96650.96600.96590.9356
1920 × 1080, JPEG 800.99110.99080.99130.9719
1920 × 1080, noise0.65640.65540.66530.5259
1920 × 1080, blur0.99290.99240.99270.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-imageanyformat-image
structural_similarity(a, b, ...)ssim(a, b).ssim
structural_similarity(..., full=True)ssim(a, b, map=True); see The map
gradient=TrueNo replacement
win_size, gaussian_weights, sigmaNo options. The window is Gaussian, 11 × 11, with sigma 1.5
use_sample_covarianceNo option. The value is False
data_rangeNo option. The inputs are 8-bit, and the data range is 255
K1, K2No options. The values are 0.01 and 0.03
channel_axisNo option; see Color and alpha
Image.open(path) and np.asarrayGive the encoded PNG file, or decode it with decode or decode_file
skimage.color.rgb2grayNo call. ssim calculates the luma; see Color and alpha
ValueError for images of different sizesImageSizeMismatchError, a subclass of ValueError
ValueError when win_size is larger than the imageValueError 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.

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

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:

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

Gray uint8 arrays
Decoded RGBA images
Decode two PNG files
Show the data as a table
OperationPackageTime
Gray uint8 arraysscikit-image, defaults88.5 ms
Gray uint8 arraysscikit-image, ssim settings117.0 ms
Gray uint8 arraysanyformat-image, with to_raw22.1 ms
Gray uint8 arraysanyformat-image, with to_raw, one thread80.5 ms
Decoded RGBA imagesscikit-image, ssim settings, on the luma132.0 ms
Decoded RGBA imagesanyformat-image7.7 ms
Decoded RGBA imagesanyformat-image, one thread67.0 ms
Decode two PNG filesPillow convert("L"), scikit-image, defaults166.0 ms
Decode two PNG filesPillow convert("L"), scikit-image, ssim settings190.0 ms
Decode two PNG filesanyformat-image23.7 ms
Decode two PNG filesanyformat-image, one thread93.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.