Deep dives

Types of visual diffing

Exact, tolerance-based, shift-tolerant, structural, hash-based and layout-aware comparison, what each type measures, what it ignores and what its numbers mean, with pixelmatch, odiff, Resemble.js, looks-same, SSIM and the hosted services as examples.

How image diffing works explains the two limits every tool exposes: a color tolerance per pixel and a maximum diff ratio per image. This deep dive is about the ideas behind them. Dozens of tools sit on a handful of approaches, and the approach matters more than the library: it decides what a threshold means, why anti-aliasing does or does not show up in your diffs, and which kinds of change the comparison can never see. The libraries below are examples of each type, not a catalog.

What every comparison decides

Every comparator answers the same questions, and the types differ in how:

  1. Are these two pixels the same color? A color metric turns two RGBA values into a distance and a tolerance decides how far apart "the same" may be. The metric sets the scale of the tolerance, which is why 0.1 in one tool is not 0.1 in another.
  2. Is this differing pixel just anti-aliasing? Text and diagonal edges are drawn with partially covered pixels whose exact values depend on the font engine and the rasterizer. A comparison either detects such pixels and ignores them, absorbs them with a blunter tolerance, or counts them.
  3. How much is too much, and what do I report? A count of differing pixels, a percentage, a boolean with bounding boxes, a similarity score, or a verdict from a service. The maximum diff ratio of the learn chapter only makes sense where the comparison reports a count.

A smaller fourth question is what happens when the images differ in size: a thrown error, a failed comparison with a diff image anyway, or a comparison of the overlapping region.

Exact comparison

The simplest type: a pixel differs if any channel differs at all. Flutter's golden tests work this way (matchesGoldenFile with the default LocalFileComparator requires an exact match, reports diffPercent and writes four images on failure), and so does swift-snapshot-testing with its defaults (precision and perceptualPrecision both 1), Paparazzi's pixelperfect differ, Resemble.js with ignore: 'nothing', and any pixel-based tool whose threshold is set to 0.

Exact comparison has no false negatives and, on a stable renderer, few false positives. Flutter makes it workable by controlling the renderer: the test font (Ahem) and software rendering remove the sources of drift in the first place. On a browser screenshot taken on a different machine, the same strictness flags every anti-aliased letter edge, which is why most web tools add a tolerance. Flutter has no tolerance in the framework, but the goldenFileComparator documentation shows the pattern for one: a subclass whose compare accepts a diffPercent below a chosen value.

Tolerance-based pixel diffing

The mainstream type, and the one behind most tools you will meet. Each pixel pair gets a color distance and counts as different when the distance exceeds a tolerance; the differing pixels are counted, painted into a diff image and compared with a limit. What separates the examples is the color distance, the anti-aliasing handling and the reporting.

The color distance

  • Weighted luminance and chroma (YIQ). pixelmatch, the reference implementation for the JavaScript ecosystem, converts both pixels to YIQ (NTSC luminance plus two chroma axes), weights the squared differences (0.5053·ΔY² + 0.299·ΔI² + 0.1957·ΔQ²) and compares the result with 35215 · threshold², 35215 being the largest value the metric can produce (black against white). Its threshold (0 to 1, default 0.1) is therefore a fraction of the black-white distance with a squared relation. Luminance differences weigh most, which matches how eyes work, and semi-transparent pixels are blended against a background first (white up to version 7.1, a per-pixel checkerboard since 7.2, so that two colors that only look alike over white do not pass). odiff uses the same coefficients and limit, so a given threshold means the same in both, and Chromatic's diffThreshold (default 0.063) is described as a YIQ color difference as well.
  • Perceptual color spaces. pixelmatch 8.0.0 replaced YIQ with OKLab and the HyAB distance (the absolute lightness difference plus the Euclidean chroma distance), which tracks perceived differences much better across the whole gamut. The threshold scale is unchanged, but the counts differ, so a baseline suite moving to version 8 re-measures its tolerances. At the time of writing every tool that embeds pixelmatch still runs a YIQ-era copy. looks-same goes to CIE L*a*b* and CIEDE2000, with a tolerance whose default 2.3 is the just-noticeable difference. swift-snapshot-testing uses Core Image's CILabDeltaE when perceptualPrecision is below 1: a pixel passes when its ΔE is at most (1 − perceptualPrecision) × 100, so 0.98 allows a ΔE of 2, and the docs say 0.98 to 0.99 "mimics the precision of the human eye".
  • Per-channel RGB. Resemble.js predates pixelmatch and reasons in plain RGB: red, green, blue and alpha may each differ by up to 16 (on a 0 to 255 scale) plus a brightness rule (0.3·R + 0.59·G + 0.11·B between minBrightness 16 and maxBrightness 240). Its ignore presets change the numbers: nothing is exact, less is the default, antialiasing widens the channels to 32 and turns the anti-aliasing logic on, colors compares brightness only (so a hue change passes) and alpha ignores alpha. Dropbox's differ, under Roborazzi, uses the plain Euclidean distance between two RGBA colors (maxDistance; differ's own default is 0.001, Roborazzi's default comparator uses 0.007).

The practical consequence: a tolerance copied from one tool's docs into another's config is a guess. A fraction of the black-white distance, a per-channel integer and a ΔE are different units.

Anti-aliasing

With a plain tolerance, raising it far enough to hide anti-aliasing also hides real tint changes. The better answer, implemented by pixelmatch, odiff, looks-same and Chromatic, is a detector from Vyšniauskas's 2009 paper "Anti-aliased pixel and intensity slope detector". For a differing pixel it looks at the 8 neighbors: if more than two are identical to the pixel it is not anti-aliasing; if there is no darker and no brighter neighbor it is not anti-aliasing; otherwise, if the darkest or the brightest neighbor has three or more identical siblings in both images, the pixel sits on an intensity slope between two flat areas and counts as anti-aliased. In pixelmatch such pixels are painted yellow and not counted (includeAA: false, the default), and a pixel that is anti-aliased in either image is excluded. looks-same adds an antialiasingTolerance (default 0; its README advises against going above 10) and an ignoreCaret option unique to it: the thin vertical bar of a blinking text cursor is recognized and ignored.

Resemble.js has a blunter rule. With ignoreAntialiasing, a pixel counts as anti-aliased when, among its 8 neighbors, more than one is strongly contrasting or more than one differs in hue by more than 0.3, or fewer than two are identical to it; such pixels are then compared by brightness alone. On large images (either side above largeImageThreshold, default 1200 px) the pass samples only every sixth row and column to stay fast.

Flutter and swift-snapshot-testing have no detector at all. The perceptual tolerance plays that role in Swift, a pinned renderer in Flutter.

What it reports

This is where the examples differ most, and it decides whether a maximum diff ratio exists:

  • A count of differing pixels: pixelmatch (and, since 8.0.0, optionally the largest count inside any windowSize×windowSize square, so scattered noise stays low while a compact change stands out; plus an ignoreMask). The ratio is up to the caller: count / (width × height). odiff returns { match, reason, diffCount, diffPercentage }, with reason: 'layout-diff' for a size mismatch when --fail-on-layout is set, plus ignore regions (--ignore x1:y1-x2:y2), a diff mask and a server mode for thousands of comparisons.
  • A percentage and more: Resemble.js returns misMatchPercentage (a string with two decimals), rawMisMatchPercentage, dimension information (it compares anyway), diffBounds and a diff image in a configurable style (flat, movement, diffOnly and others). BackstopJS, which runs Resemble through a fork of the Node port, exposes it as the per-scenario misMatchThreshold (default 0.1, meaning 0.1% of the pixels); because the value is rounded to two decimals, Backstop offers usePreciseMatching for thresholds below 0.01%.
  • A boolean plus where: looks-same returns { equal, diffBounds, diffClusters }, with clusters (shouldCluster, clustersSize, default 10) grouping nearby differing pixels into rectangles a reviewer reads as "three things changed". There is no maximum diff ratio.

Speed

pixelmatch is one pass in JavaScript with a fast path for identical images, fast enough that the PNG decode usually costs more than the comparison. Where it is not, the same algorithm is available faster: odiff is a native binary (Zig with SIMD paths) that decodes PNG, JPEG, WebP, TIFF and BMP itself and, in its own benchmark on full-page screenshots, runs about six times faster than pixelmatch; @blazediff/core is a block-optimized JavaScript port.

Who uses it

  • pixelmatch: Playwright (a vendored 2019 copy with the default threshold raised to 0.2), jest-image-snapshot (^5.1.0, its own default threshold is 0.01), @pixsame/cypress-plugin-visual-regression-diff (7.2.0, passing diffConfig straight through), Lost Pixel (5.3.0, called with threshold: 0), Loki's default engine (^5.2.0), the old reg-cli engine, and Vitest browser mode through @blazediff/core.
  • odiff: Argos, and Lost Pixel as the optional compareEngine: 'odiff'.
  • Resemble.js: BackstopJS.
  • looks-same: testplane (the renamed hermione, with its own defaults tolerance: 3.0 and antialiasingTolerance: 4) and Loki's optional engine.
  • A WebAssembly port of the YIQ comparison: reg-cli, where matchingThreshold (default 0) is the color tolerance, thresholdRate or thresholdPixel the maximum, and anti-aliasing detection stays off unless enableAntialias is set.

Shift-tolerant pixel diffing

A variation on the previous type that answers anti-aliasing and sub-pixel movement differently: a pixel matches if it matches any pixel within a small window of the other image. blink-diff (Yahoo, 2014, archived) introduced it as hShift and vShift (default 2), with a plain Euclidean RGBA delta (default 20) and an optional CIE Lab perceptual mode, and a threshold that was either a pixel count (default 500) or a percentage. The window absorbs shifted edges and most anti-aliasing at the price of missing one-pixel changes. Dropbox's differ offers the same hShift/vShift windows, which Roborazzi's README suggests increasing to work around anti-aliasing, and Paparazzi's default offbytwo differ is the same idea (a pixel may differ by a small amount), selectable next to pixelperfect, mssim, sift, flip and de2000 with a maxPercentDifference limit (default 0.01, in percent). Roborazzi's changeThreshold (default 0) fails the comparison when more than that fraction of the pixels differ.

blink-diff's three-panel composition (approved, diff, build) outlived it: jest-image-snapshot and Roborazzi still produce one. The pixelmatch README credits it and Resemble.js as inspiration.

Structural similarity

The structural similarity index (SSIM, Wang et al., 2004) does not compare pixels at all. It slides a window (11×11 by default) over both images and, for each position, compares the local mean (luminance), the local variance (contrast) and the correlation (structure) of the two patches; the per-window scores form a map and their mean is the result, 1 for identical images. It was designed to predict how humans rate image quality, which makes it good at what pixel counts are bad at: JPEG or WebP compression artifacts, slight blur, noise and sub-pixel shifts all leave the structure intact and score near 1.

ssim.js is the JavaScript implementation the tools use. It offers four algorithms: original (a line-by-line port of the reference MATLAB code), fast (mathematically equivalent, quicker), bezkrovny (downsamples first, close to but not identical with the original) and weber (the fastest, also approximate, and the library's current default). It returns mssim, the map and the time taken.

In the tools. jest-image-snapshot exposes it as comparisonMethod: 'ssim' (default 'pixelmatch'), with bezkrovny as its default algorithm and the advice to set a 1% threshold; its README describes fewer false positives and higher sensitivity to real changes as the benefit, and floating-point work that does not benefit from pixel-count fast paths as the cost. Paparazzi has an mssim differ. Playwright's source contains an undocumented ssim-cie94 comparator (a private _comparator option, not public API) that combines both types: a pixel passes if its CIE94 ΔE is at most 1, otherwise it is treated as anti-aliasing when the SSIM of a 31×31 window around it is at least 0.99, and counted as a difference otherwise.

Where SSIM fails. It is computed on luminance, so a change that keeps structure and only shifts color can score very high; Playwright's test fixtures include an "SSIM trap", a white image and a gray image that some color-weighted SSIM variants report as equal. A small change (a one-character typo) inside a large window is averaged away by everything around it that still matches, so a global mssim of 0.999 can hide exactly the regression a text-heavy UI cares about. It localizes less sharply than a pixel diff, it is slower, and its score is not a count, so "0.5% of the pixels may differ" has no SSIM equivalent. The honest use is an image that is expected to differ in rendering details but not in content: charts, photos, canvases, scaled images.

Perceptual hashes

A perceptual hash reduces the whole image to a short fingerprint. pHash downscales to grayscale, takes a discrete cosine transform, keeps the low frequencies and encodes which are above the median into a 64-bit value; two images are compared by the Hamming distance between their hashes, the number of differing bits. blockhash does the same with block mean values instead of a DCT. Both are robust to scaling, compression, small rotations and blur, which is what they were built for: finding copies and near-duplicates in large collections.

That robustness is exactly why they do not fit regression testing. A hash cannot say where the difference is, and a changed label, a missing icon or a wrong number in one table cell moves at most a bit or two, well inside the distance scaling noise also produces. They fit a coarse question ("is this the same screenshot family, or did the page change completely?"), de-duplication of baselines, or a cheap first pass before a real comparison. Among visual regression tools, VexFlow's test suite uses a pHash distance with a threshold to flag changed renderings; the mainstream web tools do not use hashing.

Hosted and layout-aware comparison

The services compare on their servers and document the knobs, not the code. Most of them run a tolerance-based pixel diff underneath and add what a library cannot: regions, layout modes and review workflows. What follows is what their public docs state.

  • Applitools exposes match levels, the only widely used example of a type that is not about pixels. Exact is a pixel-to-pixel comparison the docs do not recommend for ordinary use. Strict, the default, is described as a perceptual comparison and is most effective for regression tests on one browser and OS with mostly static content. Content (now Ignore Colors) is Strict without color differences. Layout compares the structure and relative positioning of elements and is meant for dynamic content. The recommended practice is Strict globally with Layout or Ignore Colors regions where needed.
  • Chromatic measures color difference in the YIQ color space between the same coordinates in both snapshots; diffThreshold (0 to 1, default 0.063) is the per-pixel tolerance, settable per project, component, story or test. It detects anti-aliased pixels and ignores them unless diffIncludeAntiAliasing: true. pauseAnimationAtEnd, delay and cropToViewport control the capture, not the comparison.
  • Percy documents capture options (widths, default 375 and 1280; minHeight, default 1024; percyCSS; enableJavaScript) and region algorithms: standard (pixel-based, with strictness presets and a diffSensitivity), layout, ignore, and intelliignore for images, with a diff-sensitivity slider whose default is 20%. The underlying pixel algorithm is not described.
  • Argos states that it runs odiff twice with anti-aliasing detection on: a tolerant pass (color threshold 0.15, discarded when fewer than 20 pixels or 0.02% of the image changed) and a color-sensitive pass (0.0225, counted only when at least 3% of the image changed); the higher score wins. Its threshold (0 to 1, default 0.5) scales those tolerances: 0 is zero tolerance, 1 doubles them.

The types side by side

TypeMeasuresAnti-aliasingReportsExamples
Exactany channel differencenot handled; pin the rendererfraction or count of pixelsFlutter goldens, swift-snapshot-testing defaults, Paparazzi pixelperfect
Tolerance, weighted color (YIQ, OKLab)squared weighted distance as a fraction of black-whiteslope detector, on by defaultcount of differing pixelspixelmatch, odiff, Chromatic, reg-cli, pixsame (pixelmatch 7.2.0)
Tolerance, perceptual ΔECIEDE2000 or CIE Lab ΔEslope detector (looks-same) or the tolerance itself (Swift)boolean with bounds and clusters, or pass/fail on matching fractionlooks-same, swift-snapshot-testing
Tolerance, per-channel RGBinteger tolerance per channel plus brightnesscoarse neighbor rule, sampled on large imagesmismatch percentage, bounds, styled diffResemble.js (BackstopJS)
Shift-tolerantmatch within a small pixel windowabsorbed by the windowpixel or percent threshold, composite imageblink-diff, Dropbox differ (Roborazzi), Paparazzi offbytwo
Structuralluminance, contrast and structure per windowabsorbed by the windowmean score 0 to 1 and a mapssim.js (jest-image-snapshot, Paparazzi)
Perceptual hashDCT or block means of a downscaled grayscalenot applicableHamming distance, no locationpHash, blockhash (VexFlow's tests)
Layout-aware, hostedelement structure, regions, match levelshandled server sideverdict in an appApplitools, Percy, Chromatic, Argos

How to choose

Text-heavy UIs. Anti-aliasing detection is the feature that matters: without it, every letter edge is a candidate difference. The weighted-color family (pixelmatch, odiff, Chromatic) and looks-same have the slope detector; Resemble's rule is coarser; structural comparison dilutes a changed word inside its windows; exact comparison has none and relies on a pinned renderer. Pick a detector-equipped type and pin the renderer: the detector removes the pixels that sit on the slope, not the glyphs that were hinted differently.

Compression artifacts and resampled images. Pixel comparisons see JPEG blocks and scaling noise as thousands of small differences, and raising the color tolerance hides a tint change along with them. Structural similarity is the right instrument here because the structure survives the artifact, and a perceptual ΔE tolerance is second best. Better still is to avoid the problem: screenshot as PNG, never scale before comparing.

Cross-browser and cross-OS. No type solves this; rendering differences are real differences. What helps is a comparison that reports where (looks-same's clusters, odiff's diff lines, any diff image) so a reviewer can tell a hinting change from a layout change quickly, a layout-aware mode (Applitools' Layout level) when the question is "did anything move", and separate baselines per platform, which the manifest records as platform and renderer.

Why the two limits mean different things per type. The color tolerance of the learn chapter is a fraction of the black-white distance in pixelmatch, a per-channel integer in Resemble, ΔE units in looks-same, 1 − ΔE/100 in swift-snapshot-testing and an RGBA distance in differ; the same 0.1 is strict in one and meaningless in another. The maximum diff ratio exists only where the comparison counts: pixel types count pixels, Resemble reports a percentage, looks-same a boolean with clusters, structural comparison a similarity score, the services a verdict. That is why the manifest stores the tolerance together with the metric it belongs to (comparison.colorMetric, comparison.colorThreshold) and stores the ratio only where the writer knows it (comparison.maxDiffRatio, comparison.diffRatio).

Try them yourself

The online diff tool takes two images and compares them with several of these approaches side by side (exact, pixelmatch, Resemble.js, SSIM, perceptual hash), with their options exposed, so you can watch the same pair of screenshots pass one type and fail another before you commit to a tolerance.

Sources