Debian Codegraph @

test/common/pixelmatch/contrib/PIL.py

raw
1 # Copyright (c) 2019, Mapbox, Wu Haotian
2 # Copyright (c) 2026, Freya Gustavsson
3 # SPDX-License-Identifier: ISC
4 """Functions to facilitate direct comparison of PIL.Image instances"""
5
6 from collections.abc import Collection
7 from typing import Optional
8
9 import PIL.Image
10 from PIL.Image import Image
11
12 from pixelmatch import core
13 from pixelmatch.types import ImageArea, RGBTuple
14
15
16 def pixelmatch(
17 img1: Image,
18 img2: Image,
19 output: Optional[Image] = None,
20 threshold: float = 0.1,
21 includeAA: bool = False,
22 alpha: float = 0.1,
23 aa_color: RGBTuple = (255, 255, 0),
24 diff_color: RGBTuple = (255, 0, 0),
25 diff_mask: bool = False,
26 fail_fast: bool = False,
27 masked_areas: Collection[ImageArea] = [],
28 masked_areas_color: RGBTuple = (0, 255, 0),
29 ) -> int:
30 """
31 Compares two images, writes the output diff and returns the number of mismatched pixels.
32 Serves the same purpose as pixelmatch.pixelmatch, but takes PIL.Images as input instead
33 of raw image data.
34
35 :param img1: PIL.Image data to compare with img2. Must be the same size as img2
36 :param img2: PIL.Image data to compare with img1. Must be the same size as img1
37 :param output: RGBA Image to write the diff to. Must be the same size as img1
38 :param threshold: matching threshold (0 to 1); smaller is more sensitive, defaults to 0.1
39 :param includeAA: whether or not to skip anti-aliasing detection, ie if includeAA is True,
40 detecting and ignoring anti-aliased pixels is disabled. Defaults to False
41 :param alpha: opacity of original image in diff output, defaults to 0.1
42 :param aa_color: tuple of RGB color of anti-aliased pixels in diff output,
43 defaults to (255, 255, 0) (yellow)
44 :param diff_color: tuple of RGB color of the color of different pixels in diff output,
45 defaults to (255, 0, 0) (red)
46 :param diff_mask: whether or not to draw the diff over a transparent background (a mask),
47 defaults to False
48 :param fail_fast: if true, will return after first different pixel. Defaults to false
49 :param masked_areas: collection of areas to ignore in (x, y, x_delta, y_delta)
50 :param masked_areas_color: tuple of RGB color of masked out pixels in diff output,
51 defaults to (0, 255, 0) (green)
52 :return: number of pixels that are different or 1 if fail_fast == true
53 """
54 width, height = img1.size
55 img1_rgba = img1.convert("RGBA")
56 img2_rgba = img2.convert("RGBA")
57 img1_bytes = img1_rgba.tobytes()
58 img2_bytes = img2_rgba.tobytes()
59
60 # Fast path: byte-identical images have no diff
61 if img1_bytes == img2_bytes:
62 if output is not None and not diff_mask:
63 _draw_grayscale(img1_rgba, alpha, output)
64 return 0
65
66 # core.pixelmatch doesn't read output_data, so initialize with zeros;
67 # img1 should be the same size as output (and will error in .frombytes otherwise)
68 output_data = bytearray(len(img1_bytes)) if output is not None else None
69
70 diff_pixels = core.pixelmatch(
71 list(img1_bytes),
72 list(img2_bytes),
73 width,
74 height,
75 # bytearray is MutableSequence[int], not MutableSequence[int | float];
76 # safe because draw_pixel() only ever writes int values
77 output_data, # type: ignore[arg-type]
78 threshold=threshold,
79 includeAA=includeAA,
80 alpha=alpha,
81 aa_color=aa_color,
82 diff_color=diff_color,
83 diff_mask=diff_mask,
84 fail_fast=fail_fast,
85 masked_areas=masked_areas,
86 masked_areas_color=masked_areas_color,
87 )
88
89 if output_data is not None and output is not None:
90 output.frombytes(bytes(output_data), "raw", "RGBA")
91
92 return diff_pixels
93
94
95 def _draw_grayscale(img_rgba: Image, alpha: float, output: Image) -> None:
96 """Draw a grayscale version of img_rgba blended with white into output."""
97 luminance = img_rgba.convert("L")
98 # Opaque pixels get weight `alpha`, transparent pixels get 0.
99 blend_weight = img_rgba.getchannel("A").point(lambda x: int(x * alpha))
100 white = PIL.Image.new("L", img_rgba.size, 255)
101 # Where mask is high, show luminance; where low, show white.
102 blended = PIL.Image.composite(image1=luminance, image2=white, mask=blend_weight)
103 output.paste(PIL.Image.merge("RGBA", (blended, blended, blended, white)))