Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): preserve VideoBoxes temporal axis when indexing (#5613)

NIKHILd15741e2c232
diff --git a/changelog.d/+migration-042.fixed.md b/changelog.d/+migration-042.fixed.md
index 60e56ee58..5b339f3ca 100644
--- a/changelog.d/+migration-042.fixed.md
+++ b/changelog.d/+migration-042.fixed.md
@@ -3,6 +3,5 @@ inherited from `Boxes` and pass `as_padded_sequence=True` to `to_tensor`, but th
override declared only `mode`, so every call on a `VideoBoxes` failed -- including the containers
`AugmentationSequential` builds for video box inputs. The override now accepts and forwards the
keyword; it only changes a list-backed container, and a `VideoBoxes` built from a
-`(B, T, N, 4, 2)` tensor is not one, so no working call changes its result. Indexing a
-`VideoBoxes` still drops `temporal_channel_size`, which is the remaining half of #4249.
+`(B, T, N, 4, 2)` tensor is not one, so no working call changes its result.
(#4176, #4365)
diff --git a/changelog.d/5613.breaking.md b/changelog.d/5613.breaking.md
new file mode 100644
index 000000000..d38a4fbc3
--- /dev/null
+++ b/changelog.d/5613.breaking.md
@@ -0,0 +1,7 @@
+Indexing a `VideoBoxes` now selects videos instead of rows of its flattened `(B * T, N, 4, 2)` storage.
+`video_boxes[i]` used to hold row `i` of that storage, `(N, 4, 2)` (frame `i % T` of video `i // T`), without
+`temporal_channel_size`; it is now video `i` with all `T` frames, `(T, N, 4, 2)`, and its `to_tensor()` is
+`(1, T, N, 4, 2)`. Slices, integer tensors and boolean masks index videos too, so a boolean mask has length `B`:
+a length-`B * T` mask, which used to select frames, now raises `IndexError`. Index assignment follows the same
+rule: `video_boxes[i] = other` used to write row `i` of the flattened storage and now writes all `T` frames of
+video `i`.
diff --git a/changelog.d/5613.fixed.md b/changelog.d/5613.fixed.md
new file mode 100644
index 000000000..1c766a763
--- /dev/null
+++ b/changelog.d/5613.fixed.md
@@ -0,0 +1,2 @@
+Indexing a `VideoBoxes` now returns a `VideoBoxes` that keeps `temporal_channel_size`, so `video_boxes[i].to_tensor()`
+no longer raises `AttributeError`.
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 103b44801..2100cab89 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -1052,16 +1052,15 @@ class VideoBoxes(Boxes):
:meth:`Boxes.from_tensor` does for ``'vertices_plus'``.
- :meth:`to_tensor` accepts every :class:`Boxes` mode and restores the temporal axis
(``to_tensor('xyxy')`` is :math:`(B, T, N, 4)`).
+ - Indexing selects the video batch axis while preserving the temporal axis. An integer index returns a
+ one-video :class:`VideoBoxes` so :meth:`to_tensor` keeps the shape :math:`(1, T, \ldots)`. Index
+ assignment, ``video_boxes[key] = other``, writes the same whole videos.
- A transformation matrix is :math:`(B \cdot T, 3, 3)`; a :math:`(3, 3)` matrix raises ``ValueError``
unless :math:`B \cdot T = 1`.
- :meth:`transform_boxes`, :meth:`translate`, :meth:`clamp`, :meth:`filter_boxes_by_area` and
:meth:`merge` return a new :class:`VideoBoxes`; :meth:`pad`, :meth:`unpad`, :meth:`to` and
:meth:`type` update ``self`` in place.
- .. warning::
- Indexing returns a wrapper without :attr:`temporal_channel_size`, so its :meth:`to_tensor` raises
- ``AttributeError``: `#4249 <https://github.com/kornia/kornia/issues/4249>`_.
-
Attributes:
temporal_channel_size: Number of frames :math:`T` stored with the boxes.
@@ -1107,6 +1106,29 @@ class VideoBoxes(Boxes):
out.temporal_channel_size = temporal_channel_size
return out
+ def __getitem__(self, key: slice | int | torch.Tensor) -> VideoBoxes:
+ r"""Select videos while preserving the temporal axis.
+
+ An integer or scalar tensor keeps a singleton video-batch dimension. Slices, integer tensors, and boolean
+ tensors follow the corresponding PyTorch indexing behavior on the video-batch axis.
+ """
+ batch_size = self._data.shape[0] // self.temporal_channel_size
+ video_data = self._data.view(batch_size, self.temporal_channel_size, *self._data.shape[1:])
+ selected = video_data[key]
+ if selected.ndim == self._data.ndim:
+ selected = selected.unsqueeze(0)
+
+ out = type(self)(selected.flatten(0, 1), False)
+ out._mode = self._mode
+ out.temporal_channel_size = self.temporal_channel_size
+ return out
+
+ 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:])
+ return self
+
def to_tensor(
self, mode: Optional[str] = None, as_padded_sequence: bool = False
) -> torch.Tensor | list[torch.Tensor]:
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 1955e101d..d3cb8c365 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -2117,14 +2117,68 @@ class TestVideoBoxes(BaseTester):
assert transformed.temporal_channel_size == 3
self.assert_close(transformed.to_tensor(), boxes, atol=0.0, rtol=0.0)
- def test_wart_indexing_drops_the_temporal_size_4249(self, device, dtype):
- # kornia#4249: Boxes.__getitem__ builds the result with type(self)(...) and never sets
- # temporal_channel_size, so the sliced wrapper's to_tensor fails. Invert when #4249 is fixed.
- video_boxes = VideoBoxes.from_tensor(self._sample_video_boxes(device, dtype, batch=2, time=3, n_boxes=1))
- frame = video_boxes[0]
- assert isinstance(frame, VideoBoxes)
- with pytest.raises(AttributeError, match="temporal_channel_size"):
- frame.to_tensor()
+ def test_getitem_preserves_the_temporal_axis_4249(self, device, dtype):
+ boxes = self._sample_video_boxes(device, dtype, batch=2, time=3, n_boxes=1)
+ boxes[1] += 1.0
+ video_boxes = VideoBoxes.from_tensor(boxes)
+
+ first = video_boxes[0]
+ assert isinstance(first, VideoBoxes)
+ assert first.temporal_channel_size == 3
+ self.assert_close(first.to_tensor(), boxes[:1], atol=0.0, rtol=0.0)
+
+ selected = video_boxes[torch.tensor([1, 0], device=device)]
+ assert isinstance(selected, VideoBoxes)
+ assert selected.temporal_channel_size == 3
+ self.assert_close(selected.to_tensor(), boxes[[1, 0]], atol=0.0, rtol=0.0)
+
+ @staticmethod
+ def _numbered_video_boxes(device, dtype, batch: int = 3, time: int = 2) -> torch.Tensor:
+ # Every frame is shifted by 10 * its flattened index, so a swapped or flattened frame changes the values.
+ offsets = 10.0 * torch.arange(batch * time, device=device, dtype=dtype).view(batch, time, 1, 1, 1)
+ return TestVideoBoxes._sample_video_boxes(device, dtype, batch=batch, time=time, n_boxes=2) + offsets
+
+ @staticmethod
+ def _video_key(kind: str, device):
+ return {
+ "int": 1,
+ "negative": -1,
+ "scalar": torch.tensor(2, device=device),
+ "slice": slice(1, None),
+ "step": slice(None, None, 2),
+ "long": torch.tensor([2, 0], device=device),
+ "mask": torch.tensor([True, False, True], device=device),
+ "empty": torch.zeros(3, dtype=torch.bool, device=device),
+ }[kind]
+
+ @pytest.mark.parametrize("kind", ["int", "negative", "scalar", "slice", "step", "long", "mask", "empty"])
+ def test_convention_indexing_selects_whole_videos_4249(self, kind, device, dtype):
+ # Convention pin: every key kind selects videos on the B axis and keeps all T frames in order; an integer
+ # or 0-d key keeps a batch of one.
+ boxes = self._numbered_video_boxes(device, dtype)
+ key = self._video_key(kind, device)
+ videos = torch.arange(3, device=device)[key].reshape(-1)
+
+ selected = VideoBoxes.from_tensor(boxes)[key]
+
+ assert isinstance(selected, VideoBoxes)
+ assert selected.temporal_channel_size == 2
+ self.assert_close(selected.to_tensor(), boxes[videos], atol=0.0, rtol=0.0)
+
+ @pytest.mark.parametrize("kind", ["int", "negative", "scalar", "slice", "step", "long", "mask", "empty"])
+ def test_convention_index_assignment_writes_whole_videos_4249(self, kind, device, dtype):
+ # Convention pin: assignment takes the same key as indexing, so video_boxes[key] = other[key] copies
+ # whole videos and leaves the other videos untouched.
+ boxes = self._numbered_video_boxes(device, dtype)
+ key = self._video_key(kind, device)
+ videos = torch.arange(3, device=device)[key].reshape(-1)
+ target = VideoBoxes.from_tensor(torch.zeros_like(boxes))
+
+ target[key] = VideoBoxes.from_tensor(boxes)[key]
+
+ expected = torch.zeros_like(boxes)
+ expected[videos] = boxes[videos]
+ self.assert_close(target.to_tensor(), expected, atol=0.0, rtol=0.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