π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(io): handle empty PNG transparency chunks (#5858)
Karnajeet Gosavi4c22daf83bd2
diff --git a/changelog.d/5823.added.md b/changelog.d/5823.added.mdindex 12c7c8365..a6ede0275 100644--- a/changelog.d/5823.added.md+++ b/changelog.d/5823.added.md@@ -3,7 +3,5 @@ The `kornia.io` and `kornia.image` API documentation states their conventions: tmemory, the pixel frame, rounding and clipping of the drawing functions, the value ranges of the terminalprinters, and the supported dtypes for `Image.to_gray()`. The conventions page gains a *Files and arrays* section,with the load types and a table mapping OpenCV's, Pillow's and torchvision's readers, writers and converters onto-kornia's, and a *Drawing* section. Two known defects-are documented: `write_image` raises a bare `Exception` and leaves an empty or truncated file for an image with zero-height or width (#5770), and `load_image` raises a `ValueError` that does not name the file for an 8-bit palette PNG-with an empty `tRNS` chunk, under every type except `UNCHANGED` (#5851).+kornia's, and a *Drawing* section. One known defect is documented: `write_image` raises a bare `Exception` and+leaves an empty or truncated file for an image with zero height or width (#5770).diff --git a/changelog.d/5858.fixed.md b/changelog.d/5858.fixed.mdnew file mode 100644index 000000000..5b11ef99e--- /dev/null+++ b/changelog.d/5858.fixed.md@@ -0,0 +1 @@+Palette PNGs with an empty transparency chunk now load with opaque palette entries.diff --git a/kornia/io/io.py b/kornia/io/io.pyindex 8b86a9ca2..18b8d2435 100644--- a/kornia/io/io.py+++ b/kornia/io/io.py@@ -177,8 +177,9 @@ def _apply_png_palette_and_transparency(path_file: Path, image: torch.Tensor) ->table = colorsif trns is not None:alpha = torch.full((colors.shape[0],), 255, dtype=torch.uint8)- listed = torch.frombuffer(bytearray(trns), dtype=torch.uint8)[: colors.shape[0]]- alpha[: listed.numel()] = listed+ if trns:+ listed = torch.frombuffer(bytearray(trns), dtype=torch.uint8)[: colors.shape[0]]+ alpha[: listed.numel()] = listedtable = torch.cat([colors, alpha[:, None]], dim=1)indices = image[0].long()if indices.numel() and int(indices.max()) >= table.shape[0]:@@ -326,9 +327,10 @@ def load_image(1 and 3 ``float32`` channels in [0, 1]. ``UNCHANGED`` keeps the file's channels and dtype, so a 16-bit PNGor TIFF loads as ``uint16`` and a float TIFF as ``float32``; the other types raise for such a file.- Channels are in RGB order, with alpha last. Under every type except ``UNCHANGED``, an 8-bit palette PNG- loads as its colours and a PNG ``tRNS`` chunk counts as alpha; ``RGBA8`` keeps the alpha (255 for an- opaque file), and the other types composite it over white, rounded to the nearest level. ``UNCHANGED``- returns a palette PNG's indices and keeps an alpha channel as stored.+ loads as its colours and a PNG ``tRNS`` chunk counts as alpha; palette entries the chunk does not list, all+ of them for an empty chunk, are opaque. ``RGBA8`` keeps the alpha (255 for an opaque file), and the other+ types composite it over white, rounded to the nearest level. ``UNCHANGED`` returns a palette PNG's indices+ and keeps an alpha channel as stored.- ``GRAY8`` and ``GRAY32`` convert a colour file with :func:`~kornia.color.rgb_to_grayscale`.- The pixels come back as stored: the EXIF orientation is ignored.- The extension, in any letter case, chooses the decoder; the file content does not. The file is decoded on@@ -337,9 +339,6 @@ def load_image(JPEG; these, a truncated file and, under every type except ``UNCHANGED``, a malformed palette or``PLTE``/``tRNS`` chunk raise ``ValueError``.- :ref:`Files and arrays <image-io-conventions>` maps OpenCV's and Pillow's loaders onto the load types.- - Known defect: under every type except ``UNCHANGED``, an 8-bit palette PNG with an empty ``tRNS`` chunk- raises the ``ValueError`` of ``torch.frombuffer``, whose message does not name the file, instead of loading- as its colours (`#5851 <https://github.com/kornia/kornia/issues/5851>`_).Args:path_file: Path to an image file in a format kornia-rs decodes, such as JPEG, PNG, TIFF or WebP; thediff --git a/tests/core/test_module.py b/tests/core/test_module.pyindex c0e3f28f2..6b735141b 100644--- a/tests/core/test_module.py+++ b/tests/core/test_module.py@@ -628,7 +628,11 @@ 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"])+ @pytest.mark.parametrize(+ "transparency",+ [None, bytes([255, 128]), bytes([0]), b""], # PIL writes the last two as a 1-byte and an empty tRNS chunk+ ids=["rgb", "rgba", "rgba-one-entry", "rgba-empty-trns-5851"],+ )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))diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.pyindex d2d84bbc3..f2d37369d 100644--- a/tests/io/test_io_image.py+++ b/tests/io/test_io_image.py@@ -26,6 +26,7 @@ import numpy as npimport pytestimport torch+from kornia.color import rgb_to_grayscalefrom kornia.core.exceptions import ShapeError, TypeCheckError, ValueCheckErrorfrom kornia.io import ImageLoadType, load_image, write_imagefrom kornia.io.io import _read_jpeg_components, _read_png_chunks@@ -307,6 +308,38 @@ class TestIndexedPng:assert out.shape == (4, 2, 3)assert out[3].tolist() == [[255, 128, 0], [255, 0, 128]]+ @pytest.mark.parametrize(+ "load_type",+ [ImageLoadType.GRAY8, ImageLoadType.RGB8, ImageLoadType.RGBA8, ImageLoadType.GRAY32, ImageLoadType.RGB32],+ )+ def test_empty_trns_chunk_keeps_palette_entries_opaque(self, tmp_path: Path, load_type) -> None:+ path = tmp_path / "empty_trns.png"+ write_indexed_png(path, PALETTE_INDICES, PALETTE, alpha=b"")++ out = load_image(path, load_type)++ expected_rgb = torch.tensor([PALETTE[i] for i in PALETTE_INDICES.flatten()], dtype=torch.uint8).T.reshape(+ 3, 2, 3+ )+ if load_type == ImageLoadType.RGBA8:+ assert out.shape == (4, 2, 3)+ assert out[3].tolist() == [[255, 255, 255], [255, 255, 255]]+ torch.testing.assert_close(out[:3], expected_rgb)+ elif load_type == ImageLoadType.RGB8:+ assert out.shape == (3, 2, 3)+ torch.testing.assert_close(out, expected_rgb)+ elif load_type == ImageLoadType.RGB32:+ assert out.shape == (3, 2, 3)+ expected = expected_rgb.float() / 255.0+ torch.testing.assert_close(out, expected)+ elif load_type == ImageLoadType.GRAY8:+ assert out.shape == (1, 2, 3)+ torch.testing.assert_close(out, torch.tensor([[[76, 150, 226], [29, 226, 150]]], dtype=torch.uint8))+ else:+ assert out.shape == (1, 2, 3)+ expected = rgb_to_grayscale(expected_rgb.float() / 255.0)+ torch.testing.assert_close(out, expected)+def test_rgb8_composites_transparent_palette_entries_over_white(self, tmp_path: Path) -> None:path = tmp_path / "indexed_trns.png"write_indexed_png(path, PALETTE_INDICES, PALETTE, alpha=bytes([0, 128]))