π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(io): read 16-bit grayscale and RGBA PNGs with the 16-bit decoder (#5258)
Mohammad Hijjawi16abf7ee9b51
diff --git a/changelog.d/5258.fixed.md b/changelog.d/5258.fixed.mdnew file mode 100644index 000000000..91f3f068f--- /dev/null+++ b/changelog.d/5258.fixed.md@@ -0,0 +1 @@+`load_image` now loads 16-bit grayscale and 16-bit RGBA PNGs as `uint16` with `ImageLoadType.UNCHANGED` instead of raising a decoder error; the 8-bit load types, including the default `RGB32`, now raise a `NotImplementedError` that points at `UNCHANGED` for such files.diff --git a/kornia/io/io.py b/kornia/io/io.pyindex 2a81e2342..964973ae6 100644--- a/kornia/io/io.py+++ b/kornia/io/io.py@@ -48,10 +48,11 @@ class ImageLoadType(Enum):_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"-def _read_png_color_type(path_file: Path) -> int | None:- """Read the color type byte from a PNG file header.+def _read_png_header(path_file: Path) -> tuple[int, int] | None:+ """Read the bit depth and color type bytes from a PNG file header.- Returns None if the file is truncated or has an invalid PNG signature.+ Returns ``(bit_depth, color_type)``, in that order, or None if the file is truncated or has an invalid PNG+ signature.PNG color types: 0=Grayscale, 2=RGB, 3=Indexed, 4=Grayscale+Alpha, 6=RGBA."""with open(path_file, "rb") as f:@@ -59,7 +60,7 @@ def _read_png_color_type(path_file: Path) -> int | None:header = f.read(26)if len(header) < 26 or header[:8] != _PNG_SIGNATURE:return None- return header[25]+ return header[24], header[25]# Map PNG color type byte to kornia_rs read mode.@@ -90,12 +91,15 @@ def _load_image_to_tensor(path_file: Path, device: Union[str, torch.device, Noneif path_file.suffix.lower() in [".jpg", ".jpeg"]:img = _rs_io.read_image_jpegturbo(str(path_file))elif path_file.suffix.lower() == ".png":- color_type = _read_png_color_type(path_file)# None (truncated/invalid header) intentionally falls through to read_image+ bit_depth, color_type = _read_png_header(path_file) or (None, None)mode = _PNG_COLOR_TYPE_TO_MODE.get(color_type)if mode is None or mode == "rgb":# RGB is the default of read_image; use it for unknown types tooimg = _rs_io.read_image(str(path_file))+ elif bit_depth == 16:+ # the u8 reader rejects a 16-bit buffer; UNCHANGED loads keep it as uint16+ img = _rs_io.read_image_png_u16(str(path_file), mode)else:img = _rs_io.read_image_png_u8(str(path_file), mode)else:diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.pyindex 9fed97b17..bb5569e41 100644--- a/tests/io/test_io_image.py+++ b/tests/io/test_io_image.py@@ -34,6 +34,13 @@ def create_random_img8_torch(height: int, width: int, channels: int, device=Nonereturn (torch.rand(channels, height, width, device=device) * 255).to(torch.uint8)+def write_random_png_u16(path: Path, mode: str) -> None:+ """Write a random 16-bit PNG, ``"mono"`` (grayscale) or ``"rgba"``; ``write_image`` cannot write RGBA."""+ channels = {"mono": 1, "rgba": 4}[mode]+ img_np = np.random.randint(0, 65535, (4, 5, channels)).astype(np.uint16) # noqa: NPY002+ kornia_rs.io.write_image_png_u16(str(path), img_np, mode=mode)++@pytest.fixture(scope="session")def png_image(tmp_path_factory):"""RGB PNG written locally so load tests do not depend on the network."""@@ -144,6 +151,15 @@ class TestIoImage:assert torch.equal(rgba[:3], torch.full((3, 2, 2), 64, dtype=torch.uint8))assert torch.equal(rgba[3], torch.full((2, 2), 255, dtype=torch.uint8))+ def test_unchanged_loads_an_8_bit_grayscale_png_as_one_uint8_channel(self, tmp_path: Path) -> None:+ img = create_random_img8_torch(4, 5, 1)+ path = tmp_path / "image.png"+ write_image(path, img)+ loaded = load_image(path, ImageLoadType.UNCHANGED)+ assert loaded.dtype == torch.uint8+ assert loaded.shape == (1, 4, 5)+ assert torch.equal(loaded, img)+@pytest.mark.parametrize("ext", ["jpg"])@pytest.mark.parametrize("channels", [3])def test_write_image(self, device, tmp_path, ext, channels):@@ -269,6 +285,54 @@ class TestWiderThanUint8Decodes:assert loaded.dtype == dtypeassert torch.equal(loaded, img)+ def test_unchanged_loads_a_16_bit_grayscale_png(self, tmp_path):+ img = torch.randint(0, 65535, (1, 4, 5), dtype=torch.int32).to(torch.uint16)+ path = tmp_path / "image.png"+ write_image(path, img)+ loaded = load_image(path, ImageLoadType.UNCHANGED)+ assert loaded.dtype == torch.uint16+ assert torch.equal(loaded, img)++ def test_unchanged_loads_a_16_bit_rgba_png(self, tmp_path):+ img_np = np.random.randint(0, 65535, (4, 5, 4)).astype(np.uint16) # noqa: NPY002+ path = tmp_path / "image.png"+ kornia_rs.io.write_image_png_u16(str(path), img_np, mode="rgba")+ loaded = load_image(path, ImageLoadType.UNCHANGED)+ assert loaded.dtype == torch.uint16+ assert torch.equal(loaded, torch.from_numpy(img_np).permute(2, 0, 1))++ @pytest.mark.parametrize("mode", ["mono", "rgba"])+ def test_16_bit_png_goes_to_the_16_bit_reader(self, tmp_path, monkeypatch, mode):+ """kornia_rs's ``read_image`` also decodes these files, so the dtype alone cannot show which reader ran."""+ path = tmp_path / "image.png"+ write_random_png_u16(path, mode)+ calls = []+ real = kornia_rs.io.read_image_png_u16++ def spy(*args, **kwargs):+ calls.append(args[1])+ return real(*args, **kwargs)++ monkeypatch.setattr(kornia_rs.io, "read_image_png_u16", spy)+ assert load_image(path, ImageLoadType.UNCHANGED).dtype == torch.uint16+ assert calls == [mode]++ @pytest.mark.parametrize("mode", ["mono", "rgba"])+ @pytest.mark.parametrize("load_type", [t for t in ImageLoadType if t != ImageLoadType.UNCHANGED])+ def test_eight_bit_load_types_reject_a_16_bit_png(self, tmp_path, mode, load_type):+ path = tmp_path / "image.png"+ write_random_png_u16(path, mode)+ expected = rf"decoded to torch\.uint16, and ImageLoadType\.{load_type.name} .*ImageLoadType\.UNCHANGED"+ with pytest.raises(NotImplementedError, match=expected):+ load_image(path, load_type)++ @pytest.mark.parametrize("mode", ["mono", "rgba"])+ def test_default_load_type_rejects_a_16_bit_png(self, tmp_path, mode):+ path = tmp_path / "image.png"+ write_random_png_u16(path, mode)+ with pytest.raises(NotImplementedError, match=r"decoded to torch\.uint16, and ImageLoadType\.RGB32"):+ load_image(path)+@pytest.mark.parametrize("load_type", [ImageLoadType.RGB8, ImageLoadType.GRAY8, ImageLoadType.RGB32])def test_eight_bit_load_types_reject_a_float_decode(self, tmp_path, load_type):path = tmp_path / "image.tiff"