Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): let crop_by_indices, RandomCrop and RandomResizedCrop take an empty batch (#4741)

Dipak Chaudhari96bb19dcaac1
diff --git a/changelog.d/4741.fixed.md b/changelog.d/4741.fixed.md
new file mode 100644
index 000000000..53c38ca50
--- /dev/null
+++ b/changelog.d/4741.fixed.md
@@ -0,0 +1 @@
+`crop_by_indices`, `RandomCrop` and `RandomResizedCrop` return an empty batch for an empty batch instead of raising `IndexError: list index out of range`.
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index bd4792c4e..240fc2f9a 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -471,7 +471,15 @@ def crop_by_indices(
# every loop iteration β€” the coordinates index Python-level slicing, so they must be host ints.
x1l, x2l, y1l, y2l = torch.stack([x1, x2, y1, y2], dim=0).tolist()
- if x1l.count(x1l[0]) == B and x2l.count(x2l[0]) == B and y1l.count(y1l[0]) == B and y2l.count(y2l[0]) == B:
+ # ``B > 0``: an empty batch has no first box to compare against, and takes the general path below,
+ # which returns an empty ``(0, C, *size)`` tensor (#4429).
+ if (
+ B > 0
+ and x1l.count(x1l[0]) == B
+ and x2l.count(x2l[0]) == B
+ and y1l.count(y1l[0]) == B
+ and y2l.count(y2l[0]) == B
+ ):
out = input_tensor[..., y1l[0] : y2l[0], x1l[0] : x2l[0]]
if size is not None and out.shape[-2:] != size:
return resize(
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index 9f8618671..87072fde9 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -1042,21 +1042,20 @@ class TestConventionAugmentationBase2D(BaseTester):
@pytest.mark.parametrize(
"name,error,message",
[
- ("RandomCrop", IndexError, "list index out of range"),
("LongestMaxSize", KeyError, "output_size"),
("RandomAutoContrast", ValueError, "Invalid input tensor, it is empty."),
],
)
- def test_wart_zero_batch_raises_in_three_exception_families_4429(self, name, error, message, device, dtype):
+ def test_wart_zero_batch_raises_in_two_exception_families_4429(self, name, error, message, device, dtype):
# Wart pin (#4429): `B = 0` is not uniformly "empty in, empty out". These representative
# augmentations raise through distinct failure paths; RandomAutoContrast is a deliberate validation
- # error and the others expose implementation details.
+ # error and the other exposes an implementation detail.
# Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu):
- # RandomCrop IndexError('list index out of range'), LongestMaxSize KeyError('output_size'),
- # RandomAutoContrast ValueError('Invalid input tensor, it is empty.').
- # Normalize used to be a fourth family; #4681 fixed it.
+ # LongestMaxSize KeyError('output_size'), RandomAutoContrast ValueError('Invalid input tensor, it is
+ # empty.').
+ # Normalize used to be a further family, fixed by #4681; RandomCrop's IndexError from
+ # crop_by_indices was another.
builders = {
- "RandomCrop": lambda: K.RandomCrop((4, 6), p=1.0),
"LongestMaxSize": lambda: K.LongestMaxSize(16, p=1.0),
"RandomAutoContrast": lambda: K.RandomAutoContrast(p=1.0),
}
@@ -1066,11 +1065,9 @@ class TestConventionAugmentationBase2D(BaseTester):
@pytest.mark.parametrize(
("augmentation", "shape"),
[
- pytest.param(
- lambda: K.RandomCrop((4, 6), p=1.0),
- (0, 3, 4, 6),
- marks=pytest.mark.xfail(strict=True, raises=IndexError, reason="Tracked in #4429"),
- ),
+ pytest.param(lambda: K.RandomCrop((4, 6), p=1.0), (0, 3, 4, 6), id="RandomCrop"),
+ pytest.param(lambda: K.RandomCrop((8, 10), pad_if_needed=True, p=1.0), (0, 3, 8, 10), id="RandomCrop-pad"),
+ pytest.param(lambda: K.RandomResizedCrop((4, 4), p=1.0), (0, 3, 4, 4), id="RandomResizedCrop"),
pytest.param(
lambda: K.LongestMaxSize(16, p=1.0),
(0, 3, 12, 16),
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index afdf0e2f0..d86b3020d 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -448,6 +448,17 @@ class TestCropByIndices(BaseTester):
expected = op(img, torch.tensor([[[0, 0], [1, 0], [1, 1], [0, 1]]]))
self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)
+ @pytest.mark.parametrize("size", [(2, 3), None])
+ def test_crop_by_indices_empty_batch(self, size, device, dtype):
+ # Empty in, empty out (#4429): the uniform-box fast path read the first box of an empty batch
+ # and raised IndexError. With ``size`` the output takes that size; without it there is no box
+ # to infer one from, so the spatial dimensions are zero.
+ img = torch.rand(0, 3, 5, 4, device=device, dtype=dtype)
+ src_box = torch.zeros(0, 4, 2, device=device, dtype=torch.int64)
+ out = kornia.geometry.transform.crop_by_indices(img, src_box, size=size)
+ assert out.shape == (0, 3, *(size or (0, 0)))
+ assert out.dtype == dtype
+
def test_crop_by_indices_variable_sizes_exception(self, device, dtype):
img = torch.rand(2, 3, 20, 20, device=device, dtype=dtype)
src_box = torch.tensor(