Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 855332a

Browse files
committed
Fixed SVG-as-text image comparison tests.
SVG-as-text tests make make the figure background transparent, but its colour (i.e. under the transparent mask) is actually black. Before the expected and actual images are compared, they are converted from RGBA to RGB, which makes them both completely black (since the text is also black). As a result, the test passes even if the expected and actual images differ. Not ignoring the transparency layer fixes this problem: discard the transparency layer (if any) only if the image is opaque.
1 parent 40dea5a commit 855332a

File tree

2 files changed

+814
-753
lines changed

2 files changed

+814
-753
lines changed

lib/matplotlib/testing/compare.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,16 @@ def calculate_rms(expected_image, actual_image):
371371
# 16-bit depth, as Pillow converts these to RGB incorrectly.
372372

373373

374+
def _load_image(path):
375+
img = Image.open(path)
376+
# In an RGBA image, if the smallest value in the alpha channel is 255, all
377+
# values in it must be 255, meaning that the image is opaque. If so,
378+
# discard the alpha channel so that it may compare equal to an RGB image.
379+
if img.mode != "RGBA" or img.getextrema()[3][0] == 255:
380+
img = img.convert("RGB")
381+
return np.asarray(img)
382+
383+
374384
def compare_images(expected, actual, tol, in_decorator=False):
375385
"""
376386
Compare two "image" files checking differences within a tolerance.
@@ -435,9 +445,9 @@ def compare_images(expected, actual, tol, in_decorator=False):
435445
actual = convert(actual, cache=True)
436446
expected = convert(expected, cache=True)
437447

438-
# open the image files and remove the alpha channel (if it exists)
439-
expected_image = np.asarray(Image.open(expected).convert("RGB"))
440-
actual_image = np.asarray(Image.open(actual).convert("RGB"))
448+
# open the image files
449+
expected_image = _load_image(expected)
450+
actual_image = _load_image(actual)
441451

442452
actual_image, expected_image = crop_to_same(
443453
actual, actual_image, expected, expected_image)
@@ -486,9 +496,8 @@ def save_diff_image(expected, actual, output):
486496
output : str
487497
File path to save difference image to.
488498
"""
489-
# Drop alpha channels, similarly to compare_images.
490-
expected_image = np.asarray(Image.open(expected).convert("RGB"))
491-
actual_image = np.asarray(Image.open(actual).convert("RGB"))
499+
expected_image = _load_image(expected)
500+
actual_image = _load_image(actual)
492501
actual_image, expected_image = crop_to_same(
493502
actual, actual_image, expected, expected_image)
494503
expected_image = np.array(expected_image).astype(float)

0 commit comments

Comments
 (0)