Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): expand palette PNG image paths (#5833)

Keshav Chhabra78a43985af60
diff --git a/changelog.d/5833.breaking.md b/changelog.d/5833.breaking.md
new file mode 100644
index 000000000..8e69af62d
--- /dev/null
+++ b/changelog.d/5833.breaking.md
@@ -0,0 +1,5 @@
+`ImageModuleMixIn`, `ImageSequential` and `AugmentationSequential` now load an 8-bit palette PNG image path as its RGB
+colors, or RGBA colors when the file has a `tRNS` chunk, as they already did for the same image passed as a PIL object.
+Previously such a path produced one channel of palette indices divided by 255. A palette PNG path whose palette is too
+short for its pixels, or whose `tRNS` chunk fails its CRC check, used to load as indices and now raises `ValueError`,
+as `kornia.io.load_image` does for that file under every type except `UNCHANGED`.
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index 9ea445ecb..ab71e54e3 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -21,6 +21,7 @@ import math
import os
import sys
from functools import wraps
+from pathlib import Path
from typing import Any, Callable, List, Literal, Optional, Tuple, Union
import torch
@@ -269,12 +270,14 @@ class ImageModuleMixIn:
Supports image path, numpy array, PIL image, and raw tensor. A NumPy array of shape :math:`(H, W)`,
:math:`(H, W, C)` or :math:`(B, H, W, C)` becomes :math:`(C, H, W)` or :math:`(B, C, H, W)`, with one channel
for :math:`(H, W)`; a PIL image converts like its NumPy array, except that a palette image (mode ``P`` or
- ``PA``) is converted to RGB, or RGBA when it has transparency, first. An integer image is divided by the maximum
- of its dtype (``uint8`` by 255, ``uint16`` by 65535, a PIL mode ``I`` image by the ``int32`` maximum); a signed
- image maps to ``[iinfo.min / iinfo.max, 1]``, so its negative values stay negative. A ``bool`` image becomes 0
- and 1, and a floating image keeps its values; integer and ``bool`` images become the default floating dtype.
- When this mixin belongs to a stateful :class:`torch.nn.Module`, the converted image is moved to the module's
- device and first floating parameter or buffer dtype. A tensor is returned unchanged.
+ ``PA``) is converted to RGB, or RGBA when it has transparency, first. A path is loaded with
+ :func:`kornia.io.load_image` as ``ImageLoadType.UNCHANGED``, which keeps 16-bit data and alpha, except that
+ an 8-bit palette PNG converts like its PIL image, to RGB, or RGBA when it has a ``tRNS`` chunk. An integer image
+ is divided by the maximum of its dtype (``uint8`` by 255, ``uint16`` by 65535, a PIL mode ``I`` image by the
+ ``int32`` maximum); a signed image maps to ``[iinfo.min / iinfo.max, 1]``, so its negative values stay negative.
+ A ``bool`` image becomes 0 and 1, and a floating image keeps its values; integer and ``bool`` images become the
+ default floating dtype. When this mixin belongs to a stateful :class:`torch.nn.Module`, the converted image is
+ moved to the module's device and first floating parameter or buffer dtype. A tensor is returned unchanged.
Args:
x: The input to convert.
@@ -285,8 +288,16 @@ class ImageModuleMixIn:
"""
if isinstance(x, str):
from kornia.io import ImageLoadType, load_image # pylint: disable=C0415
+ from kornia.io.io import ( # pylint: disable=C0415
+ _apply_png_palette_and_transparency,
+ _read_png_header,
+ )
- image = _image_to_float(load_image(x, ImageLoadType.UNCHANGED))
+ path = Path(x)
+ image = load_image(path, ImageLoadType.UNCHANGED)
+ if path.suffix.lower() == ".png" and (_read_png_header(path) or (None, None))[1] == 3:
+ image = _apply_png_palette_and_transparency(path, image)
+ image = _image_to_float(image)
elif isinstance(x, torch.Tensor):
return x
elif isinstance(x, np.ndarray): # type: ignore
diff --git a/tests/core/test_module.py b/tests/core/test_module.py
index 5f4d5bedd..e16e3b692 100644
--- a/tests/core/test_module.py
+++ b/tests/core/test_module.py
@@ -626,6 +626,79 @@ class TestImageModuleConversions(BaseTester):
out = _Identity().to_tensor(str(path))
self.assert_close(out, torch.tensor([1.0, 0.2, 0.0]).view(3, 1, 1).expand(3, 4, 6))
+ @pytest.mark.parametrize("transparency", [None, bytes([255, 128])], ids=["rgb", "rgba"])
+ def test_to_tensor_palette_png_path_matches_pil_5807(self, tmp_path, transparency):
+ path = tmp_path / "palette.png"
+ image = PILImage.new("P", (2, 1))
+ image.putdata([0, 1])
+ image.putpalette([255, 0, 0, 0, 255, 0] + [0] * (256 * 3 - 6))
+ if transparency is not None:
+ image.info["transparency"] = transparency
+ image.save(path)
+
+ module = _Identity()
+ from_path = module.to_tensor(str(path))
+ with PILImage.open(path) as from_pil:
+ expected = module.to_tensor(from_pil)
+
+ expected_channels = 3 if transparency is None else 4
+ assert from_path.shape == (expected_channels, 1, 2)
+ self.assert_close(from_path, expected, rtol=0.0, atol=0.0)
+
+ @pytest.mark.parametrize(
+ "factory",
+ [
+ pytest.param(lambda: ImageSequential(torch.nn.Identity()), id="core-image-sequential"),
+ pytest.param(lambda: AugmentationImageSequential(torch.nn.Identity()), id="augmentation-image-sequential"),
+ pytest.param(lambda: AugmentationSequential(RandomHorizontalFlip(p=0.0)), id="augmentation-sequential"),
+ ],
+ )
+ @pytest.mark.parametrize("transparency", [None, bytes([255, 128])], ids=["rgb", "rgba"])
+ def test_sequential_palette_png_path_matches_pil_5807(self, tmp_path, factory, transparency):
+ path = tmp_path / "palette.png"
+ image = PILImage.new("P", (2, 1))
+ image.putdata([0, 1])
+ image.putpalette([255, 0, 0, 0, 255, 0] + [0] * (256 * 3 - 6))
+ if transparency is not None:
+ image.info["transparency"] = transparency
+ image.save(path)
+
+ module = factory()
+ from_path = module(str(path))
+ with PILImage.open(path) as from_pil:
+ expected = module(from_pil)
+
+ expected_channels = 3 if transparency is None else 4
+ assert from_path.shape[-3:] == (expected_channels, 1, 2)
+ self.assert_close(from_path, expected, rtol=0.0, atol=0.0)
+
+ @pytest.mark.parametrize(
+ "name, mode, pixels, transparency, channels",
+ [
+ ("palette.PNG", "P", [0, 1], bytes([255, 128]), 4), # the suffix matches in any letter case
+ ("gray_key.png", "L", [7, 200], 7, 1), # a tRNS colour key is not a palette: PIL keeps mode L
+ ("rgb_key.png", "RGB", [(255, 0, 0), (0, 0, 255)], (255, 0, 0), 3), # and mode RGB
+ ],
+ ids=["palette-upper-case-suffix", "gray-colour-key", "rgb-colour-key"],
+ )
+ def test_to_tensor_png_path_expands_palettes_only_5807(self, tmp_path, name, mode, pixels, transparency, channels):
+ path = tmp_path / name
+ image = PILImage.new(mode, (2, 1))
+ image.putdata(pixels)
+ if mode == "P":
+ image.putpalette([255, 0, 0, 0, 255, 0] + [0] * (256 * 3 - 6))
+ image.info["transparency"] = transparency
+ image.save(path, format="PNG")
+
+ module = _Identity()
+ from_path = module.to_tensor(str(path))
+ with PILImage.open(path) as from_pil:
+ assert "transparency" in from_pil.info
+ expected = module.to_tensor(from_pil)
+
+ assert from_path.shape == (channels, 1, 2)
+ self.assert_close(from_path, expected, rtol=0.0, atol=0.0)
+
def test_to_tensor_16_bit_path_5207(self, tmp_path):
path = tmp_path / "rgb16.png"
write_image(str(path), torch.tensor([65535, 13107, 0], dtype=torch.uint16).view(3, 1, 1).expand(3, 4, 6))