pixelmatch

repository·main·Indexed 27 days ago

https://github.com/mapbox/pixelmatch

A small, fast, and dependency-free JavaScript library for pixel-level image comparison. Designed for Node.js and browser environments, pixelmatch works with raw typed arrays and features accurate anti-aliased pixel detection and perceptual color difference metrics. It includes a function for comparing image data and a command-line tool for comparing PNG images.

Tokens
1.7K
Snippets
5
Records
10
Agent score
91%

What's inside pixelmatch

  1. Use windowed diff density for noise robustness

    main

    By default, pixelmatch returns the total count of differing pixels. If you set windowSize: N in the options, the function returns the largest number of diff pixels found in any N×N sliding window.

    This is useful for making tests robust to scattered noise (like GPU dithering or sub-pixel anti-aliasing) that doesn't pack densely. You can then fail a test based on density (result / N² > tau) which remains comparable across different image sizes.

  2. Install pixelmatch

    main

    You can install pixelmatch via npm for Node.js environments or use it directly in the browser via an ESM CDN.

    Node.js:

    npm install pixelmatch

    Browser:

    <script type="module">
    	import pixelmatch from 'https://esm.run/pixelmatch';
    npm install pixelmatch
  3. Example: pixelmatch in Node.js

    main

    This example demonstrates how to use pixelmatch with pngjs to compare two PNG files and save the difference to a new file.

    import fs from 'fs';
    import {PNG} from 'pngjs';
    import pixelmatch from 'pixelmatch';
    
    const img1 = PNG.sync.read(fs.readFileSync('img1.png'));
    const img2 = PNG.sync.read(fs.readFileSync('img2.png'));
    const {width, height} = img1;
    const diff = new PNG({width, height});
    
    pixelmatch(img1.data, img2.data, diff.data, width, height, {threshold: 0.1});
    
    fs.writeFileSync('diff.png', PNG.sync.write(diff));
    import fs from 'fs';
    import {PNG} from 'pngjs';
    import pixelmatch from 'pixelmatch';
    
    const img1 = PNG.sync.read(fs.readFileSync('img1.png'));
    const img2 = PNG.sync.read(fs.readFileSync('img2.png'));
    const {width, height} = img1;
    const diff = new PNG({width, height});
    
    pixelmatch(img1.data, img2.data, diff.data, width, height, {threshold: 0.1});
    
    fs.writeFileSync('diff.png', PNG.sync.write(diff));
  4. Example: pixelmatch in Browsers

    main

    This example shows how to use pixelmatch with the Canvas API ImageData objects.

    const img1 = img1Context.getImageData(0, 0, width, height);
    const img2 = img2Context.getImageData(0, 0, width, height);
    const diff = diffContext.createImageData(width, height);
    
    pixelmatch(img1.data, img2.data, diff.data, width, height, {threshold: 0.1});
    
    diffContext.putImageData(diff, 0, 0);
    const img1 = img1Context.getImageData(0, 0, width, height);
    const img2 = img2Context.getImageData(0, 0, width, height);
    const diff = diffContext.createImageData(width, height);
    
    pixelmatch(img1.data, img2.data, diff.data, width, height, {threshold: 0.1});
    
    diffContext.putImageData(diff, 0, 0);
  5. Use the pixelmatch API

    main

    The pixelmatch function compares two images and returns the number of mismatched pixels. It can also write the difference to an output buffer.

    Signature: pixelmatch(img1, img2, output, width, height[, options])

    Parameters:

    • img1, img2: Image data of the images to compare (Buffer, Uint8Array or Uint8ClampedArray). Image dimensions must be equal.
    • output: Image data to write the diff to, or null if no diff image is needed.
    • width, height: Width and height of the images. All three images (img1, img2, and output) must have the same dimensions.
    • options: An optional configuration object (see Configure pixelmatch options).

    Returns:

    • The number of mismatched pixels (or the maximum number of differing pixels in any N×N sliding window if windowSize is set).
    const numDiffPixels = pixelmatch(img1, img2, diff, 800, 600, {threshold: 0.1});
  6. Configure pixelmatch options

    main

    The options object allows you to fine-tune the comparison and the visual output of the diff.

    OptionTypeDefaultDescription
    thresholdnumber0.1Matching threshold (0 to 1). Smaller values make comparison more sensitive.
    includeAAbooleanfalseIf true, disables detecting and ignoring anti-aliased pixels.
    alphanumber0.1Blending factor of unchanged pixels in diff output (0 for pure white, 1 for original brightness).
    aaColor[R, G, B][255, 255, 0]Color of anti-aliased pixels in the diff output.
    diffColor[R, G, B][255, 0, 0]Color of differing pixels in the diff output.
    diffColorAlt[R, G, B]nullAlternative color for dark on light differences to differentiate "added" vs "removed" parts.
    diffMaskbooleanfalseIf true, draws the diff over a transparent background (mask) instead of the original image.
    checkerboardbooleantrueBlends semi-transparent pixels against a checkerboard pattern to avoid false matches.
    windowSizenumberInfinityIf set to N, returns the max differing pixels in any N×N sliding window instead of total count.
  7. Run pixelmatch via Command Line

    main

    Pixelmatch includes a binary for comparing PNG images directly from the terminal.

    Usage:

    pixelmatch image1.png image2.png output.png 0.1

    Note: The last argument is the threshold.

    pixelmatch image1.png image2.png output.png 0.1
  8. Use pixelmatch() to compare two images

    main

    The pixelmatch function compares two equally sized images pixel by pixel. It returns the number of mismatched pixels. If an output buffer is provided, it writes the visual difference to that buffer.

    Parameters:

    • img1: First image data (Uint8Array or Uint8ClampedArray).
    • img2: Second image data (Uint8Array or Uint8ClampedArray).
    • output: (Optional) Image data to write the diff to (Uint8Array, Uint8ClampedArray, or void).
    • width: Width of the input images.
    • height: Height of the input images.
    • options: (Optional) Configuration object for comparison behavior.

    Returns:

    • number: The number of mismatched pixels (or the maximum per-window count if options.windowSize is finite).
  9. Calculate windowed diff density with windowSize

    main
    By setting the windowSize option to a finite number, pixelmatch changes its return value. Instead of returning the total count of mismatched pixels, it returns the maximum number of mismatched pixels found within any N×N sliding window (where N is the windowSize). This is useful for detecting localized clusters of differences rather than just global pixel counts.
  10. Use the pixelmatch CLI to compare images

    main

    The pixelmatch command-line tool compares two PNG images and optionally generates a diff image highlighting the differences. It requires two input image paths and accepts optional arguments for the output path, sensitivity threshold, and anti-aliasing inclusion.

    Usage Pattern: pixelmatch <image1.png> <image2.png> [diff.png] [threshold] [includeAA]

    Arguments:

    • image1.png: Path to the first PNG image.
    • image2.png: Path to the second PNG image.
    • [diff.png]: (Optional) Path where the resulting diff PNG will be saved.
    • [threshold]: (Optional) A numeric threshold for pixel comparison.
    • [includeAA]: (Optional) A string 'true' or 'false' to include/exclude anti-aliasing in the diff. Defaults to true unless explicitly set to 'false'.

    Exit Codes:

    • 0: No differences found.
    • 64: Invalid usage (missing required arguments).
    • 65: Image dimensions do not match.
    • 66: Differences were found.