Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(io): include path in image decode errors (#5267)

Karnajeet Gosavi3ce29f8b46b1
diff --git a/changelog.d/5267.fixed.md b/changelog.d/5267.fixed.md
new file mode 100644
index 000000000..ed132880e
--- /dev/null
+++ b/changelog.d/5267.fixed.md
@@ -0,0 +1 @@
+`kornia.io.load_image` now raises a `ValueError` that names the file and keeps the decoder's reason, chained from the decoder's exception, when an image cannot be decoded (for example a truncated or corrupt PNG, JPEG or TIFF); it used to raise a bare `Exception` that did not name the file. A missing or unreadable file still raises the same `OSError` as before (`FileNotFoundError`, `PermissionError`).
diff --git a/kornia/io/io.py b/kornia/io/io.py
index 964973ae6..a5994f42d 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -88,22 +88,27 @@ def _load_image_to_tensor(path_file: Path, device: Union[str, torch.device, None
"""
# read image and return as `np.ndarray` with shape HxWxC
- if path_file.suffix.lower() in [".jpg", ".jpeg"]:
- img = _rs_io.read_image_jpegturbo(str(path_file))
- elif path_file.suffix.lower() == ".png":
- # 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 too
- img = _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)
+ try:
+ if path_file.suffix.lower() in [".jpg", ".jpeg"]:
+ img = _rs_io.read_image_jpegturbo(str(path_file))
+ elif path_file.suffix.lower() == ".png":
+ # 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 too
+ img = _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:
- img = _rs_io.read_image_png_u8(str(path_file), mode)
- else:
- img = _rs_io.read_image(str(path_file))
+ img = _rs_io.read_image(str(path_file))
+ except OSError:
+ raise # a missing or unreadable file keeps its specific type (FileNotFoundError, PermissionError, ...)
+ except Exception as e:
+ raise ValueError(f"Failed to decode image '{path_file}': {e}") from e
# convert the image to torch.Tensor with shape CxHxW
img_t = image_to_tensor(img, keepdim=True)
@@ -190,6 +195,11 @@ def load_image(
Return:
Image torch.Tensor with shape :math:`(3,H,W)`.
+ Raises:
+ ValueError: if the file cannot be decoded, for example a truncated or corrupt image or an unsupported format.
+ The message names the file and keeps the decoder's reason; the decoder's exception is the ``__cause__``.
+ OSError: if the file cannot be read, for example ``FileNotFoundError`` when it does not exist.
+
"""
if not isinstance(path_file, Path):
path_file = Path(path_file)
diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.py
index bb5569e41..a0740c38b 100644
--- a/tests/io/test_io_image.py
+++ b/tests/io/test_io_image.py
@@ -16,6 +16,7 @@
#
import io
+import re
from pathlib import Path
import kornia_rs
@@ -73,6 +74,36 @@ def images_fn(png_image, jpg_image):
class TestIoImage:
+ @pytest.mark.parametrize(
+ ("suffix", "channels", "dtype"),
+ [
+ (".png", 1, torch.uint8), # read_image_png_u8
+ (".png", 1, torch.uint16), # read_image_png_u16
+ (".png", 3, torch.uint8), # read_image (RGB PNG)
+ (".jpg", 3, torch.uint8), # read_image_jpegturbo
+ (".tiff", 3, torch.uint8), # read_image (any other extension)
+ ],
+ ids=["png-gray8", "png-gray16", "png-rgb8", "jpg-rgb8", "tiff-rgb8"],
+ )
+ def test_truncated_image_decode_error_includes_path(self, suffix, channels, dtype, tmp_path: Path) -> None:
+ pixels = (torch.arange(channels * 64 * 64, dtype=torch.int32) * 37 % 251).reshape(channels, 64, 64).to(dtype)
+ path = tmp_path / f"truncated_{channels}c_{str(dtype).removeprefix('torch.')}{suffix}"
+ write_image(path, pixels)
+ data = path.read_bytes()
+ path.write_bytes(data[: len(data) // 2])
+
+ with pytest.raises(ValueError, match=re.escape(path.name)) as exc_info:
+ load_image(path, ImageLoadType.UNCHANGED)
+
+ assert exc_info.value.__cause__ is not None
+ assert str(exc_info.value.__cause__) in str(exc_info.value)
+
+ @pytest.mark.parametrize(("suffix", "error"), [(".png", FileNotFoundError), (".jpg", OSError), (".tiff", OSError)])
+ def test_missing_file_keeps_its_os_error(self, suffix, error, tmp_path: Path) -> None:
+ # a missing file is not a decode failure: callers catching FileNotFoundError or OSError keep working
+ with pytest.raises(error):
+ load_image(tmp_path / f"missing{suffix}")
+
def test_smoke(self, tmp_path: Path) -> None:
height, width = 4, 5
img_th: torch.Tensor = create_random_img8_torch(height, width, 3)