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

[ssim.js](https://github.com/obartra/ssim) calculates the structural
similarity (SSIM) of two images in JavaScript. `ssim` of
`@swc/anyformat-image` calculates the same metric in native code:

- It uses the Gaussian window of ssim.js 5: 11 × 11 pixels with sigma 1.5,
  the same constants, and the mean over the same pixels. With
  `downsample: false`, the scores of ssim.js 5.0.1 were within 0.001 of the
  scores of `ssim` on the [test images](#scores). The default options of
  ssim.js give different scores. See [Scores](#scores).
- It decodes PNG files itself, so you do not need pngjs.
- It has an asynchronous form that does not block the event loop, and it
  uses all CPU cores. On a 1920 × 1080 image, it was about 13 times faster
  than ssim.js 5 with `downsample: false` (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 scikit-image in Python, read
[Migrate SSIM from scikit-image](https://anyformat.swc.rs/guide/python/migrate-from-scikit-image.md).

ssim.js runs in browsers. `@swc/anyformat-image` is a package for Node.js.
Keep ssim.js for code that runs in a browser.

## Compare two PNG files

With pngjs and ssim.js:

```js
import fs from 'node:fs'
import { PNG } from 'pngjs'
import { ssim } from 'ssim.js'

const img1 = PNG.sync.read(fs.readFileSync('expected.png'))
const img2 = PNG.sync.read(fs.readFileSync('actual.png'))

const { mssim } = ssim(img1, img2)
if (mssim < 0.98) throw new Error(`SSIM is ${mssim}`)
```

With `@swc/anyformat-image`:

```js
import fs from 'node:fs/promises'
import { ssim } from '@swc/anyformat-image'

const result = await ssim(
  await fs.readFile('expected.png'),
  await fs.readFile('actual.png'),
)
if (result.ssim < 0.98) throw new Error(`SSIM is ${result.ssim}`)
```

The two programs do not give the same score: by default, ssim.js makes the
images smaller first. Before you keep a threshold such as `0.98`, read
[Scores](#scores).

`ssim` also accepts raw images. A pngjs `PNG` object and an `ImageData`
object are valid raw images, so you can give the images that you give to
ssim.js today:

```js
import { ssimSync } from '@swc/anyformat-image'

const result = ssimSync(img1, img2)
result.ssim // compare with mssim of ssim.js
```

## Scores

`ssim` calculates the SSIM at full resolution. By default, ssim.js does not:

- **Downsampling.** ssim.js makes the images smaller by an integer factor
  before it calculates the SSIM. The factor is
  `Math.round(Math.min(width, height) / 256)`, so a 1920 × 1080 image is
  calculated at 480 × 270, and a 512 × 512 image at 256 × 256. An image with
  a short side of less than 384 pixels is not downsampled. Downsampling
  hides small differences, so the scores are higher.
- **Algorithm.** The default algorithm of ssim.js 3 is `'weber'`, which uses
  a box window and not a Gaussian window. ssim.js 5 uses the Gaussian window
  by default, as `ssim` does.

These scores were measured with Node.js 24 and ssim.js 5.0.1 and 3.5.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.

| Image, change        | `ssim` | ssim.js 5, `downsample: false` | ssim.js 5, defaults | ssim.js 3, defaults |
| -------------------- | ------ | ------------------------------ | ------------------- | ------------------- |
| 512 × 512, JPEG 30   | 0.9311 | 0.9307                         | 0.9809              | 0.9888              |
| 512 × 512, JPEG 80   | 0.9713 | 0.9710                         | 0.9958              | 0.9968              |
| 512 × 512, noise     | 0.7451 | 0.7443                         | 0.8947              | 0.9243              |
| 512 × 512, blur      | 0.9378 | 0.9368                         | 0.9805              | 0.9867              |
| 1920 × 1080, JPEG 30 | 0.9665 | 0.9660                         | 0.9926              | 0.9948              |
| 1920 × 1080, JPEG 80 | 0.9911 | 0.9908                         | 0.9991              | 0.9988              |
| 1920 × 1080, noise   | 0.6564 | 0.6554                         | 0.9165              | 0.9326              |
| 1920 × 1080, blur    | 0.9929 | 0.9924                         | 0.9989              | 0.9990              |

ssim.js 3 with `{ ssim: 'fast', downsample: false }` also gave scores within
0.001 of `ssim`. The scores of `ssim` are lower than the scores of the
defaults of ssim.js, so a threshold from ssim.js can fail images that passed
before. Do these steps:

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

If you cannot set new thresholds now, downsample the images with
[`resize`](https://anyformat.swc.rs/api/image.md#resize) before you call `ssim`. This gives scores
close to the defaults of ssim.js 5, but not the same scores. On the test
images above, the difference was 0.003 or less. There is no replacement for
the `'weber'` algorithm, which is the default of ssim.js 3.

```js
import { decode, resize, ssim } from '@swc/anyformat-image'

// Downsample by the factor of ssim.js, with an area average.
async function downsample(file) {
  const image = await decode(file)
  const factor = Math.round(Math.min(image.width, image.height) / 256)
  if (factor <= 1) return image
  return resize(image, {
    width: Math.ceil(image.width / factor),
    height: Math.ceil(image.height / factor),
  })
}

const result = await ssim(await downsample(fileA), await downsample(fileB))
```

## API mapping

| ssim.js                                              | `@swc/anyformat-image`                                                   |
| ---------------------------------------------------- | ------------------------------------------------------------------------ |
| `ssim(img1, img2)`                                   | `await ssim(img1, img2)` or `ssimSync(img1, img2)`                       |
| `ssim(img1, img2).mssim`                             | `result.ssim`                                                            |
| `ssim(img1, img2, { map: true }).ssim_map`           | `(await ssim(img1, img2, { map: true })).map`; see [The map](#the-map)   |
| `ssim_map` of ssim.js 3, which it always returns     | Pass `map: true`                                                         |
| `performance`                                        | No replacement. Measure the time with `performance.now()`                |
| `ssim: 'gaussian'` (5), `'fast'` or `'original'` (3) | The only algorithm                                                       |
| `ssim: 'weber'` or `'bezkrovny'`                     | No replacement                                                           |
| `downsample: false`                                  | The only behavior                                                        |
| `downsample: 'wang'`, `'original'`, or `'fast'`      | `resize` before `ssim`; see [Scores](#scores)                            |
| `maxSize`                                            | The target size of `resize`                                              |
| `windowSize`, `k1`, `k2`, `bitDepth`                 | No options. The values are 11, 0.01, 0.03, and 8                         |
| `rgb2grayVersion`                                    | No option; see [Grayscale and alpha](#grayscale-and-alpha)               |
| Decode the files with pngjs or a canvas first        | Give the encoded PNG files, or decode them with `decode`                 |
| An error for images of different sizes               | An error with `code` `ERR_IMAGE_SIZE_MISMATCH`                           |
| An error when the window is larger than the image    | An error with `code` `ERR_INVALID_ARG_VALUE` when a side is less than 11 |

ssim.js 5 requires Node.js 22.14 or later. `@swc/anyformat-image` requires
Node.js 18 or later.

## Grayscale and alpha

Both packages calculate the SSIM of one gray channel. They make the gray
values in different ways:

- ssim.js uses the red, green, and blue channels. It ignores the alpha
  channel. `ssim` composites each pixel over white first, so a transparent
  pixel and an opaque white pixel have the same luma. For a transparent
  image and a white image, ssim.js 5 gives about 0.0001, and `ssim` gives 1.
- ssim.js rounds the gray value of each pixel to an integer from 0 to 255.
  `ssim` uses the luma as a floating-point value, with the ITU-R BT.601
  weights `0.299 R + 0.587 G + 0.114 B`. The weights of ssim.js are almost
  the same. The small differences in the first two columns of
  [Scores](#scores) come from the rounding.

`ssim` does not compare colors. Two images with the same luma give 1. To
find changes in color, use [`compareImages`](https://anyformat.swc.rs/api/image.md#compareimages).

## The map

The SSIM map of ssim.js is a matrix of numbers. The map of `ssim` is a raw
image:

- **Size.** The map of ssim.js has only the windows that are fully in the
  image, so it is 10 pixels smaller than the image in each direction. When
  ssim.js downsamples, the map has the size of the downsampled image minus
  10 pixels. The map of `ssim` has the size of the input. At the edges, the
  filter reflects the image.
- **Values.** The map of ssim.js has the SSIM values. Each pixel of the map
  of `ssim` has `round(clamp(ssim, 0, 1) * 255)` in R, G, and B, and 255 in
  A, so the values are rounded to steps of 1/255, and negative values
  become 0.

To get the SSIM value at a pixel, as a number from 0 to 1:

```js
const { map } = await ssim(a, b, { map: true })
const value = map.data[(y * map.width + x) * 4] / 255
```

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

```js
import { writeFile } from 'node:fs/promises'
import { encode } from '@swc/anyformat-image'

await writeFile('ssim-map.png', await encode(map, { format: 'png' }))
```

## Performance

A measurement on one x86_64 Linux computer (Intel Core i7-13700F, 24
threads) with Node.js 24.22, ssim.js 5.0.1 and 3.5.0, and pngjs 7.0.0. The
inputs were the 1920 × 1080 photograph of [Scores](#scores) 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.

- @swc/anyformat-image
- ssim.js and pngjs

Raw images, full resolution

ssim.js 3, ssim: 'fast', downsample: false463.0 ms

ssim.js 5, downsample: false101.0 ms

@swc/anyformat-image7.8 ms

@swc/anyformat-image, one thread65.0 ms

Decode two PNG files, full resolution

pngjs and ssim.js 5, downsample: false236.0 ms

@swc/anyformat-image23.8 ms

@swc/anyformat-image, one thread95.0 ms

Decode two PNG files, downsampled to 480 × 270

pngjs and ssim.js 3, defaults362.0 ms

pngjs and ssim.js 5, defaults146.0 ms

@swc/anyformat-image, decode, resize, ssim34.3 ms

Show the data as a table

| Operation | Package | Time |
| --- | --- | --- |
| Raw images, full resolution | ssim.js 3, ssim: 'fast', downsample: false | 463.0 ms |
| Raw images, full resolution | ssim.js 5, downsample: false | 101.0 ms |
| Raw images, full resolution | @swc/anyformat-image | 7.8 ms |
| Raw images, full resolution | @swc/anyformat-image, one thread | 65.0 ms |
| Decode two PNG files, full resolution | pngjs and ssim.js 5, downsample: false | 236.0 ms |
| Decode two PNG files, full resolution | @swc/anyformat-image | 23.8 ms |
| Decode two PNG files, full resolution | @swc/anyformat-image, one thread | 95.0 ms |
| Decode two PNG files, downsampled to 480 × 270 | pngjs and ssim.js 3, defaults | 362.0 ms |
| Decode two PNG files, downsampled to 480 × 270 | pngjs and ssim.js 5, defaults | 146.0 ms |
| Decode two PNG files, downsampled to 480 × 270 | @swc/anyformat-image, decode, resize, ssim | 34.3 ms |


The time of ssim.js does not depend on the number of threads, because it
runs in JavaScript on one thread. In the last group, the program decodes,
resizes, and calculates in three calls, as in the example in
[Scores](#scores).
