Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): blend boxes by the frame gate in inverse_boxes (#5884)

Adarsh Mishrab94f1c5323cf
diff --git a/changelog.d/5884.fixed.md b/changelog.d/5884.fixed.md
new file mode 100644
index 000000000..153ccd760
--- /dev/null
+++ b/changelog.d/5884.fixed.md
@@ -0,0 +1 @@
+`AugmentationSequential.inverse` no longer raises `IndexError` when a `VideoSequential` child with `p < 1` skips some frames of a video bounding-box batch: the inverse now lands on exactly the frames that were transformed. `VideoBoxes` index assignment (`video_boxes[key] = other`) no longer raises for clips with no boxes.
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 3029b4c8d..b54118348 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -325,7 +325,14 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
elif to_apply.all():
output = input.transform_boxes_(transform)
else:
- output[to_apply] = input[to_apply].transform_boxes_(transform[to_apply])
+ # Indexing with `to_apply` would select whole videos on the batch axis of a
+ # :class:`VideoBoxes`, while the gate has one entry per frame. Blend on the flat
+ # storage instead, as :meth:`transform_boxes` does, so a partial gate applies the
+ # inverse to exactly the frames that were augmented.
+ applied = input.clone().transform_boxes_(transform)
+ output = input.clone()
+ output._data = self._blend_by_prob(applied.data, input.data, to_apply)
+ output._valid = self._blend_by_prob(applied._valid, input._valid, to_apply)
return output
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 6a5bb04c4..dfd25d46a 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -1155,8 +1155,10 @@ class VideoBoxes(Boxes):
def __setitem__(self, key: slice | int | torch.Tensor, value: Boxes) -> VideoBoxes:
r"""Write whole videos, selected by ``key`` on the video-batch axis as in :meth:`__getitem__`."""
size = self.temporal_channel_size
- self._data.view(-1, size, *self._data.shape[1:])[key] = value.data.view(-1, size, *value.data.shape[1:])
- self._valid.view(-1, size, self._valid.shape[-1])[key] = value._valid.view(-1, size, value._valid.shape[-1])
+ # Explicit video counts: a clip with no boxes has 0 elements, so a -1 in the view would be ambiguous.
+ n, m = self._data.shape[0] // size, value.data.shape[0] // size
+ self._data.view(n, size, *self._data.shape[1:])[key] = value.data.view(m, size, *value.data.shape[1:])
+ self._valid.view(n, size, self._valid.shape[-1])[key] = value._valid.view(m, size, value._valid.shape[-1])
return self
def to_tensor(
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index b34e3e34a..760ba183e 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -1254,6 +1254,24 @@ class TestConventionAugmentationSequential(BaseTester):
_, restored = aug.inverse(out_image, out_boxes)
self.assert_close(restored, boxes)
+ def test_video_boxes_inverse_with_partial_gate_5871(self, device, dtype):
+ torch.manual_seed(0)
+ corners = torch.tensor([[1.0, 1.0], [3.0, 1.0], [3.0, 4.0], [1.0, 4.0]], device=device, dtype=dtype)
+ boxes = corners.expand(4, 3, 2, 4, 2).clone()
+ aug = K.AugmentationSequential(
+ K.VideoSequential(K.RandomHorizontalFlip(p=0.5), data_format="BTCHW"),
+ data_keys=["input", "bbox"],
+ )
+
+ image, out_boxes = aug(torch.rand(4, 3, 1, 6, 6, device=device, dtype=dtype), boxes)
+ # The gate must mix applied and skipped frames, otherwise the round-trip proves nothing.
+ flipped = (out_boxes.data.view(4, 3, 2, 4, 2) - boxes).abs().sum(dim=(-1, -2, -3)) > 0
+ assert bool(flipped.any()), flipped.tolist()
+ assert not bool(flipped.all()), flipped.tolist()
+
+ _, restored = aug.inverse(image, out_boxes)
+ self.assert_close(restored, boxes)
+
@pytest.mark.parametrize("batch_size", [2, 3])
@pytest.mark.parametrize("keepdim,child_keepdim", [(True, False), (None, True), (False, True)])
@pytest.mark.parametrize("mask_layout", ["BHW", "BCHW"])
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index f0e42de49..078a4d697 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -2333,6 +2333,15 @@ class TestVideoBoxes(BaseTester):
expected[videos] = boxes[videos]
self.assert_close(target.to_tensor(), expected, atol=0.0, rtol=0.0)
+ def test_index_assignment_without_boxes_5871(self, device, dtype):
+ # A clip with no boxes stores (B * T, 0, 4, 2): the write still lands in place.
+ target = VideoBoxes.from_tensor(torch.zeros(3, 2, 0, 4, 2, device=device, dtype=dtype))
+ storage = target.data
+ target[1] = VideoBoxes.from_tensor(torch.zeros(1, 2, 0, 4, 2, device=device, dtype=dtype))
+ assert target.data is storage
+ assert target.data.shape == (6, 0, 4, 2)
+ assert target._valid.shape == (6, 0)
+
def test_convention_inherited_methods_split_copies_from_in_place_updates(self, device, dtype):
# Convention pin: transform_boxes, translate, clamp, filter_boxes_by_area and merge copy through
# clone, so they return a new VideoBoxes carrying the temporal size and leave the source