Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(image): handle empty batches in make_grid (#5763)

Puttala Jeevan Kumar802437d1f418
diff --git a/changelog.d/5763.fixed.md b/changelog.d/5763.fixed.md
new file mode 100644
index 000000000..0bf2a2d96
--- /dev/null
+++ b/changelog.d/5763.fixed.md
@@ -0,0 +1,4 @@
+`make_grid`, `ImageModule.show` and `ImageModule.save` no longer raise `ZeroDivisionError` for an empty batch with the
+default `n_row`: `make_grid` returns an empty grid, as it already did for an explicit `n_row`. An `n_row` below 1 now
+raises a `ValueError` naming `n_row` instead of a `ZeroDivisionError` (`n_row=0`) or an unrelated reshape error
+(negative `n_row`). (#5755)
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index 06a5bdd4d..9ea445ecb 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -449,7 +449,7 @@ class ImageModuleMixIn:
from kornia.image.utils import make_grid # pylint: disable=C0415
if n_row is None:
- n_row = math.ceil(output_image.shape[0] ** 0.5)
+ n_row = max(1, math.ceil(output_image.shape[0] ** 0.5))
out_image = make_grid(output_image, n_row, padding=2)
if backend == "pil" and display:
@@ -477,7 +477,7 @@ class ImageModuleMixIn:
from kornia.image.utils import make_grid # pylint: disable=C0415
if n_row is None:
- n_row = math.ceil(output_image.shape[0] ** 0.5)
+ n_row = max(1, math.ceil(output_image.shape[0] ** 0.5))
out_image = make_grid(output_image, n_row, padding=2)
from kornia.io import write_image # pylint: disable=C0415
diff --git a/kornia/image/utils.py b/kornia/image/utils.py
index ca9d3ecae..f16d4cd96 100644
--- a/kornia/image/utils.py
+++ b/kornia/image/utils.py
@@ -270,7 +270,9 @@ def make_grid(tensor: torch.Tensor, n_row: Optional[int] = None, padding: int =
B, C, H, W = tensor.shape
if n_row is None:
- n_row = int(torch.sqrt(torch.tensor(B, dtype=torch.float32)).ceil().item())
+ n_row = max(1, int(torch.sqrt(torch.tensor(B, dtype=torch.float32)).ceil().item()))
+ elif n_row < 1:
+ raise ValueError("n_row must be positive.")
n_col = n_row
n_row = (B + n_col - 1) // n_col
diff --git a/tests/core/test_module.py b/tests/core/test_module.py
index 83b2467c1..5f4d5bedd 100644
--- a/tests/core/test_module.py
+++ b/tests/core/test_module.py
@@ -133,6 +133,28 @@ class TestImageModuleMixIn:
img_module.save(name=save_path)
assert os.path.exists(save_path)
+ @pytest.mark.parametrize("method", ["show", "save"])
+ @pytest.mark.parametrize("n_row", [None, 0, -1])
+ def test_show_save_empty_batch_n_row(self, img_module, monkeypatch, method, n_row):
+ img_module._output_image = torch.empty(0, 3, 4, 4)
+ sink = MagicMock()
+ if method == "show":
+ monkeypatch.setattr(img_module, "to_pil", sink)
+ kwargs = {"display": False}
+ else:
+ monkeypatch.setattr("kornia.io.write_image", sink)
+ kwargs = {"name": "empty.png"}
+
+ if n_row is not None:
+ with pytest.raises(ValueError, match="n_row"):
+ getattr(img_module, method)(n_row=n_row, **kwargs)
+ sink.assert_not_called()
+ else:
+ getattr(img_module, method)(**kwargs)
+ sink.assert_called_once()
+ grid = sink.call_args.args[-1]
+ assert grid.shape == (3, 0, 4)
+
def test_to_pil_4d_tensor_returns_list(self, img_module):
# 4D (B, C, H, W) tensor -> list of PIL Images
t = torch.rand(3, 3, 16, 16)
diff --git a/tests/image/test_image_utils.py b/tests/image/test_image_utils.py
index a9712a403..d7f496b63 100644
--- a/tests/image/test_image_utils.py
+++ b/tests/image/test_image_utils.py
@@ -238,3 +238,40 @@ class TestMakeGrid(BaseTester):
def test_gradcheck(self, device):
tensor = torch.rand(3, 1, 2, 2, device=device, dtype=torch.float64)
self.gradcheck(kornia.image.make_grid, (tensor, 2, 1))
+
+
[email protected]("channels", [1, 3])
[email protected]("n_row", [None, 1, 2])
+def test_make_grid_empty(device, dtype, channels, n_row):
+ tensor = torch.empty(0, channels, 4, 4, device=device, dtype=dtype)
+
+ actual = kornia.image.make_grid(tensor, n_row=n_row)
+ reference = kornia.image.make_grid(tensor, n_row=1 if n_row is None else n_row)
+
+ assert actual.ndim == 3
+ assert actual.shape[0] == channels
+ assert actual.numel() == 0
+ assert sorted(actual.shape[1:]) == [0, (1 if n_row is None else n_row) * 6 - 2]
+ assert actual.shape == reference.shape
+ assert actual.dtype == tensor.dtype
+ assert actual.device == tensor.device
+
+
[email protected]("batch_size", [0, 3])
[email protected]("n_row", [0, -1, -2])
+def test_make_grid_invalid_n_row(device, dtype, batch_size, n_row):
+ tensor = torch.empty(batch_size, 3, 4, 4, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="n_row"):
+ kornia.image.make_grid(tensor, n_row=n_row)
+
+
[email protected]("n_row", [None, 2])
+def test_make_grid_valid(device, dtype, n_row):
+ tensor = torch.arange(3, device=device, dtype=dtype).reshape(3, 1, 1, 1)
+ expected = tensor.new_tensor([[[0, 1], [2, 0]]])
+
+ actual = kornia.image.make_grid(tensor, n_row=n_row, padding=0)
+
+ assert actual.dtype == tensor.dtype
+ assert actual.device == tensor.device
+ assert_close(actual, expected)