From fcd3eef594bb8eadce8333236440e2f9e9ccbe5f Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 7 Oct 2022 22:33:45 +1100 Subject: [PATCH] Added conversion between RGB/RGBA/RGBX and LAB --- Tests/test_image_convert.py | 11 +++++++++++ src/PIL/Image.py | 13 +++++++++++++ 2 files changed, 24 insertions(+) diff --git a/Tests/test_image_convert.py b/Tests/test_image_convert.py index 1a78f8b4c..adbd83733 100644 --- a/Tests/test_image_convert.py +++ b/Tests/test_image_convert.py @@ -242,6 +242,17 @@ def test_p2pa_palette(): assert im_pa.getpalette() == im.getpalette() +@pytest.mark.parametrize("mode", ("RGB", "RGBA", "RGBX")) +def test_rgb_lab(mode): + im = Image.new(mode, (1, 1)) + converted_im = im.convert("LAB") + assert converted_im.getpixel((0, 0)) == (0, 128, 128) + + im = Image.new("LAB", (1, 1), (255, 0, 0)) + converted_im = im.convert(mode) + assert converted_im.getpixel((0, 0))[:3] == (0, 255, 255) + + def test_matrix_illegal_conversion(): # Arrange im = hopper("CMYK") diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 6611ceb3c..5641879ac 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1027,6 +1027,19 @@ class Image: warnings.warn("Couldn't allocate palette entry for transparency") return new + if "LAB" in (self.mode, mode): + other_mode = mode if self.mode == "LAB" else self.mode + if other_mode in ("RGB", "RGBA", "RGBX"): + from . import ImageCms + + srgb = ImageCms.createProfile("sRGB") + lab = ImageCms.createProfile("LAB") + profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab] + transform = ImageCms.buildTransform( + profiles[0], profiles[1], self.mode, mode + ) + return transform.apply(self) + # colorspace conversion if dither is None: dither = Dither.FLOYDSTEINBERG