Implementation:Microsoft Playwright ImageCompare
Overview
ImageCompare implements the SSIM (Structural Similarity Index) based image comparison algorithm used as Playwright's default visual comparator for screenshot assertions.
Description
The compare function performs a sophisticated pixel-by-pixel comparison of two images using:
1. Color difference (CIE94 deltaE) for per-pixel color comparison
2. SSIM (Structural Similarity Index) for structural similarity within local windows
3. Variance analysis for detecting anti-aliased regions
The algorithm classifies each pixel as:
- Matching (gray in diff) -- structurally similar and within color threshold
- Anti-aliased (yellow in diff) -- differs but in a low-variance region (likely anti-aliasing)
- Different (red in diff) -- structurally dissimilar above the threshold
Images are padded with alternating colored borders to catch edge-region changes.
Usage
Used by the comparators module as the "ssim" comparator strategy for image assertions.
Code Reference
Source Location
packages/playwright-core/src/server/utils/image_tools/compare.ts (120 lines)
Function Signature
export function compare(
actual: Buffer,
expected: Buffer,
diff: Buffer | null,
width: number,
height: number,
options?: { maxColorDeltaE94?: number }
): number; // returns count of different pixels
Import
import { compare } from './server/utils/image_tools/compare';
I/O Contract
Inputs
actual,expected-- RGBA pixel buffersdiff-- optional output buffer for diff visualizationwidth,height-- image dimensionsmaxColorDeltaE94-- color threshold (default 1.0 = just noticeable)
Outputs
- Returns count of pixels classified as different
- Fills diff buffer with color-coded visualization if provided
Constants
SSIM_WINDOW_RADIUS = 15VARIANCE_WINDOW_RADIUS = 1
Related Pages
- Microsoft_Playwright_Comparators -- Comparator factory using this module
- Microsoft_Playwright_ColorUtils -- Color difference calculations
- Microsoft_Playwright_SsimStats -- SSIM statistical computations
- Microsoft_Playwright_ImageChannel -- Image channel separation
- Microsoft_Playwright_Pixelmatch -- Alternative pixel-level comparison