Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(io): reject a zero-sized image before writing any file (#5975)

XXXXXQ.34eedd25dfef
diff --git a/changelog.d/5975.fixed.md b/changelog.d/5975.fixed.md
new file mode 100644
index 000000000..203fbacf8
--- /dev/null
+++ b/changelog.d/5975.fixed.md
@@ -0,0 +1,3 @@
+`kornia.io.write_image` rejects an image whose height or width is zero with a `ShapeError` naming the shape,
+before the file is created. It used to reach kornia-rs, which raised a bare `Exception` and left a truncated file
+behind (#5770).
diff --git a/kornia/io/io.py b/kornia/io/io.py
index 18b8d2435..64170007d 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -419,8 +419,8 @@ def write_image(path_file: str | Path, image: torch.Tensor, quality: int = 80) -
- ``image`` is channels first. A channels-last :math:`(H, W, C)` tensor is not detected: its first axis is
read as the channels.
- :ref:`Files and arrays <image-io-conventions>` maps ``cv2.imwrite`` onto these arguments.
- - Known defect: an image with zero height or width reaches kornia-rs, which raises a bare ``Exception`` and
- leaves an empty or truncated file behind (`#5770 <https://github.com/kornia/kornia/issues/5770>`_).
+ - An image with zero height or width raises ``ShapeError`` before anything is written, so no empty or
+ truncated file is left behind.
Args:
path_file: Path with a .jpg, .jpeg, .png, .tif or .tiff extension, in any letter case.
@@ -435,7 +435,8 @@ def write_image(path_file: str | Path, image: torch.Tensor, quality: int = 80) -
TypeCheckError: if ``image`` is not a tensor or ``quality`` is not an integer (also a ``TypeError``).
ValueCheckError: if ``quality`` is outside [0, 100] (also a ``ValueError``).
BaseError: if the extension is not one of the five above.
- ShapeError: if ``image`` is not 2-D or 3-D, or the format cannot store its channels (also a ``ValueError``).
+ ShapeError: if ``image`` is not 2-D or 3-D, the height or width is not positive, or the format cannot
+ store its channels (also a ``ValueError``).
FileNotFoundError: if the directory to write into does not exist (``NotADirectoryError`` if it is a file).
NotImplementedError: if the format cannot store the dtype.
Exception: kornia-rs's bare ``Exception`` when the file cannot be created or the image cannot be encoded.
@@ -465,6 +466,14 @@ def write_image(path_file: str | Path, image: torch.Tensor, quality: int = 80) -
actual_shape=tuple(image.shape),
expected_shape=["C", "H", "W"],
)
+ # kornia-rs raises a bare Exception on a zero-sized image and leaves the truncated file behind,
+ # so reject the shape before anything is created.
+ height, width = image.shape[-2], image.shape[-1]
+ if height <= 0 or width <= 0:
+ raise ShapeError(
+ f"Cannot write an image of shape {tuple(image.shape)}: the height and width must be positive.",
+ actual_shape=tuple(image.shape),
+ )
parent = path_file.parent
if not parent.is_dir():
diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.py
index c4cfa76d8..ec1b38dbe 100644
--- a/tests/io/test_io_image.py
+++ b/tests/io/test_io_image.py
@@ -1267,16 +1267,27 @@ class TestConventionsIo:
assert written["default"] != written["q95"]
@pytest.mark.parametrize(
- ("shape", "match"),
+ "shape",
[
- ((3, 0, 4), "[Zz]ero height|non zero|invalid dimensions"),
- ((3, 4, 0), "[Zz]ero width|non zero|invalid dimensions"),
+ (3, 0, 4),
+ (3, 4, 0),
+ (1, 0, 0),
+ (0, 4),
+ (4, 0),
],
)
- def test_wart_write_image_zero_size_raises_bare_exception_5770(self, tmp_path, shape, match):
- # #5770: a zero-height or zero-width image reaches kornia-rs, whose error is a bare ``Exception``. The fix
- # should raise a kornia error (a ShapeError) before encoding, which flips this pin.
+ def test_convention_write_image_zero_size_raises_5770(self, tmp_path, shape):
+ # #5770: a zero height or width used to reach kornia-rs, which raised a bare Exception and left the
+ # truncated file behind. It is now rejected before anything is created.
for ext in ("png", "jpg", "tif"):
- with pytest.raises(Exception, match=match) as excinfo:
- write_image(tmp_path / f"zero.{ext}", torch.zeros(*shape, dtype=torch.uint8))
- assert excinfo.type is Exception
+ path = tmp_path / f"zero.{ext}"
+ with pytest.raises(ShapeError, match=re.escape(str(tuple(shape)))):
+ write_image(path, torch.zeros(*shape, dtype=torch.uint8))
+ assert not path.exists()
+
+ @pytest.mark.parametrize("shape", [(3, 1, 4), (3, 4, 1), (1, 4)])
+ def test_write_image_accepts_a_single_row_or_column_5770(self, tmp_path, shape):
+ # Only a zero extent is rejected: a 1-pixel height or width still writes.
+ path = tmp_path / "thin.png"
+ write_image(path, torch.zeros(*shape, dtype=torch.uint8))
+ assert path.stat().st_size > 0