Debian Codegraph @

src/pytest_regressions/image_regression.py

raw symbols SCIP
1 import io
2 import os
3 from functools import partial
4 from pathlib import Path
5 from typing import Any
6 from typing import Optional
7
8 import pytest
9
10 from .common import import_error_message
11 from .common import perform_regression_check
12
13
14 class ImageRegressionFixture:
15 """
16 Regression test for image objects, accounting for small differences.
17 """
18
19 def __init__(
20 self, datadir: Path, original_datadir: Path, request: pytest.FixtureRequest
21 ) -> None:
22 self.request = request
23 self.datadir = datadir
24 self.original_datadir = original_datadir
25 self.force_regen = False
26 self.with_test_class_names = False
27
28 def _load_image(self, filename: "os.PathLike[str]") -> Any:
29 """
30 Reads the image from the given file and convert it to RGB if necessary.
31 This is necessary to be used with the ImageChops module operations.
32 At this time, in this module, channel operations are only implemented
33 for 8-bit images (e.g. "L" and "RGB").
34 """
35 try:
36 from PIL import Image
37 except ModuleNotFoundError:
38 raise ModuleNotFoundError(import_error_message("Pillow"))
39
40 img = Image.open(str(filename), "r")
41 if img.mode not in ("L" or "RGB"):
42 return img.convert("RGB")
43 else:
44 return img
45
46 def _compute_manhattan_distance(self, diff_image: Any) -> float:
47 """
48 Computes a percentage of similarity of the difference image given.
49
50 :param diff_image:
51 An image in RGB mode computed from ImageChops.difference
52 """
53 try:
54 import numpy
55 except ModuleNotFoundError:
56 raise ModuleNotFoundError(import_error_message("Numpy"))
57
58 number_of_pixels = diff_image.size[0] * diff_image.size[1]
59 return float(
60 # To obtain a number in 0.0 -> 100.0
61 100.0
62 * (
63 # Compute the sum of differences
64 numpy.sum(diff_image)
65 /
66 # Divide by the number of channel differences RGB * Pixels
67 float(3 * number_of_pixels)
68 )
69 # Normalize between 0.0 -> 1.0
70 / 255.0
71 )
72
73 def _check_images_manhattan_distance(
74 self,
75 obtained_file: Path,
76 expected_file: Path,
77 expect_equal: bool,
78 diff_threshold: float,
79 ) -> None:
80 """
81 Compare two image by computing the differences spatially, pixel by pixel.
82
83 The Manhattan Distance is used to compute how much two images differ.
84
85 :param obtained_file:
86 The image with the obtained image
87
88 :param expected_file:
89 The image with the expected image
90
91 :param expect_equal:
92 If True, the images are expected to be equal, otherwise, they're expected to be
93 different.
94
95 :param diff_threshold:
96 The maximum percentage of difference accepted.
97 A value between 0.0 and 100.0
98
99 :raises AssertionError:
100 raised if they are actually different and expect_equal is False or
101 if they are equal and expect_equal is True.
102 """
103 try:
104 from PIL import ImageChops
105 except ModuleNotFoundError:
106 raise ModuleNotFoundError(import_error_message("Pillow"))
107
108 __tracebackhide__ = True
109
110 obtained_img = self._load_image(obtained_file)
111 expected_img = self._load_image(expected_file)
112
113 def check_result(equal: bool, manhattan_distance: Optional[float]) -> None:
114 if equal != expect_equal:
115 if expect_equal:
116 assert (
117 False
118 ), f"Difference between images too high: {manhattan_distance} %\n{expected_file}\n{obtained_file}"
119 else:
120 assert (
121 False
122 ), f"Difference between images too small: {manhattan_distance} %\n{expected_file}\n{obtained_file}"
123
124 # 1st check: identical
125 diff_img = ImageChops.difference(obtained_img, expected_img)
126
127 if diff_img.getbbox() is None: # Equal
128 check_result(True, None)
129
130 manhattan_distance = self._compute_manhattan_distance(diff_img)
131 equal = manhattan_distance <= diff_threshold
132 check_result(equal, manhattan_distance)
133
134 def check(
135 self,
136 image_data: bytes,
137 diff_threshold: float = 0.1,
138 expect_equal: bool = True,
139 basename: Optional[str] = None,
140 ) -> None:
141 """
142 Checks that the given image contents are comparable with the ones stored in the data directory.
143
144 :param image_data: image data
145 :param basename: basename to store the information in the data directory. If none, use the name
146 of the test function.
147 :param expect_equal: if the image should considered equal below of the given threshold. If False, the
148 image should be considered different at least above the threshold.
149 :param diff_threshold:
150 Tolerance as a percentage (1 to 100) on how the images are allowed to differ.
151 """
152 __tracebackhide__ = True
153
154 try:
155 from PIL import Image
156 except ModuleNotFoundError:
157 raise ModuleNotFoundError(import_error_message("Pillow"))
158
159 def dump_fn(target: Path) -> None:
160 image = Image.open(io.BytesIO(image_data))
161 image.save(str(target), "PNG")
162
163 perform_regression_check(
164 datadir=self.datadir,
165 original_datadir=self.original_datadir,
166 request=self.request,
167 check_fn=partial(
168 self._check_images_manhattan_distance,
169 diff_threshold=diff_threshold,
170 expect_equal=expect_equal,
171 ),
172 dump_fn=dump_fn,
173 extension=".png",
174 basename=basename,
175 force_regen=self.force_regen,
176 with_test_class_names=self.with_test_class_names,
177 )