Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(io): raise the specific OSError subclass from load_image for every format (#5362)

niukanen108a9b35d5849
diff --git a/changelog.d/5362.fixed.md b/changelog.d/5362.fixed.md
new file mode 100644
index 000000000..93e3ba13b
--- /dev/null
+++ b/changelog.d/5362.fixed.md
@@ -0,0 +1 @@
+`load_image` raises the `OSError` subclass that `open()` raises (`FileNotFoundError`, `IsADirectoryError`, `PermissionError`), naming the path, for a missing, directory or unreadable file of every format. A JPEG path raised a bare `OSError` without the file name, so did a TIFF or WebP directory or unreadable file, and a directory or unreadable file with another suffix raised `ValueError` as an unsupported format.
diff --git a/kornia/io/io.py b/kornia/io/io.py
index a5994f42d..89feeb1f7 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -89,6 +89,11 @@ def _load_image_to_tensor(path_file: Path, device: Union[str, torch.device, None
"""
# read image and return as `np.ndarray` with shape HxWxC
try:
+ # open the file first so Python raises the specific OSError subclass
+ # (FileNotFoundError, IsADirectoryError, PermissionError) naming the path
+ # for every format, instead of kornia_rs's bare OSError without the name
+ with open(path_file, "rb"):
+ pass
if path_file.suffix.lower() in [".jpg", ".jpeg"]:
img = _rs_io.read_image_jpegturbo(str(path_file))
elif path_file.suffix.lower() == ".png":
diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.py
index a0740c38b..9f398402c 100644
--- a/tests/io/test_io_image.py
+++ b/tests/io/test_io_image.py
@@ -98,12 +98,23 @@ class TestIoImage:
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)])
+ @pytest.mark.parametrize(
+ ("suffix", "error"), [(".png", FileNotFoundError), (".jpg", FileNotFoundError), (".tiff", FileNotFoundError)]
+ )
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):
+ with pytest.raises(error, match=re.escape(f"missing{suffix}")):
load_image(tmp_path / f"missing{suffix}")
+ @pytest.mark.parametrize("suffix", [".jpg", ".tiff", ".xyz"])
+ def test_directory_path_raises_os_error_naming_the_path(self, suffix, tmp_path: Path) -> None:
+ # every format path goes through open(), so a directory names itself instead of a bare OSError (.jpg, .tiff)
+ # or a ValueError for an unrecognised format (.xyz); Windows raises PermissionError for open() on a directory,
+ # POSIX raises IsADirectoryError
+ (tmp_path / f"dir{suffix}").mkdir()
+ with pytest.raises((IsADirectoryError, PermissionError), match=re.escape(f"dir{suffix}")):
+ load_image(tmp_path / f"dir{suffix}")
+
def test_smoke(self, tmp_path: Path) -> None:
height, width = 4, 5
img_th: torch.Tensor = create_random_img8_torch(height, width, 3)