π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(geometry): export and document VideoBoxes (#4016) (#4138)
Soham Saha11fd2721370a
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex 84faff2c9..65b5c963e 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -25,7 +25,7 @@ from torch import Sizefrom kornia.core.ops import eye_likefrom kornia.geometry.linalg import transform_points-__all__ = ["Boxes", "Boxes3D"]+__all__ = ["Boxes", "Boxes3D", "VideoBoxes"]def _is_floating_point_dtype(dtype: torch.dtype) -> bool:@@ -835,12 +835,44 @@ class Boxes:class VideoBoxes(Boxes):+ r"""2D boxes with an explicit temporal channel for video sequences.++ Accepts and returns box corners for a batch of videos as+ :math:`(B, T, N, 4, 2)` in ``vertices_plus`` mode. Internally the corners+ are stored flattened as :math:`(B \cdot T, N, 4, 2)`.+ :class:`~kornia.augmentation.AugmentationSequential` uses this wrapper when+ the pipeline contains a video sequential so that ``to_tensor`` restores the+ temporal axis after geometric transforms.++ Attributes:+ temporal_channel_size: Number of frames :math:`T` stored with the boxes.++ """+temporal_channel_size: int@classmethoddef from_tensor( # type: ignore[override]cls, boxes: torch.Tensor | list[torch.Tensor], validate_boxes: bool = True) -> VideoBoxes:+ r"""Create :class:`VideoBoxes` from a video box tensor.++ Args:+ boxes: Box corners with shape :math:`(B, T, N, 4, 2)` in+ ``vertices_plus`` order (top-left, top-right, bottom-right,+ bottom-left). Lists of tensors are not supported yet.+ validate_boxes: Forwarded to ``_boxes_to_quadrilaterals``. The+ ``vertices_plus`` path used here builds corners directly and+ performs no size check, so this flag currently has no effect.++ Returns:+ :class:`VideoBoxes` with :attr:`temporal_channel_size` set to+ ``boxes.size(1)``.++ Raises:+ ValueError: If ``boxes`` is a list or does not have shape+ :math:`(B, T, N, 4, 2)`.+ """if isinstance(boxes, (list,)) or (boxes.dim() != 5 or boxes.shape[-2:] != torch.Size([4, 2])):raise ValueError("Input box type is not yet supported. Please input an `BxTxNx4x2` tensor directly.")@@ -856,6 +888,16 @@ class VideoBoxes(Boxes):return outdef to_tensor(self, mode: Optional[str] = None) -> torch.Tensor | list[torch.Tensor]: # type: ignore[override]+ r"""Cast :class:`VideoBoxes` to a tensor with the temporal axis restored.++ Args:+ mode: Output box format forwarded to :meth:`Boxes.to_tensor`. When+ ``None``, uses the stored mode (``vertices_plus`` by default).++ Returns:+ Tensor shaped :math:`(B, T, \ldots)` where :math:`T` is+ :attr:`temporal_channel_size`.+ """out = super().to_tensor(mode, as_padded_sequence=False)if isinstance(out, torch.Tensor):return out.view(-1, self.temporal_channel_size, *out.shape[1:])@@ -863,6 +905,12 @@ class VideoBoxes(Boxes):return [_out.view(-1, self.temporal_channel_size, *_out.shape[1:]) for _out in out]def clone(self) -> VideoBoxes:+ """Create an independent copy of the video box container.++ Returns:+ New :class:`VideoBoxes` with cloned tensor storage and the same+ :attr:`temporal_channel_size`, mode, and batch metadata.+ """obj = type(self)(self._data.clone(), False)obj._mode = self._modeobj._N = self._Ndiff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.pyindex 60652e190..3bb6db81a 100644--- a/tests/geometry/test_boxes.py+++ b/tests/geometry/test_boxes.py@@ -20,7 +20,8 @@ from functools import partialimport pytestimport torch-from kornia.geometry.boxes import Boxes, Boxes3D+from kornia.geometry import boxes as boxes_module+from kornia.geometry.boxes import Boxes, Boxes3D, VideoBoxesfrom testing.base import BaseTester@@ -931,3 +932,68 @@ class TestTransformBoxes3D(BaseTester):return boxes.dataself.gradcheck(_wrapper_transform_boxes, (boxes.data, trans_mat))+++class TestVideoBoxes(BaseTester):+ """Public API and round-trip coverage for :class:`VideoBoxes` (#4016)."""++ @staticmethod+ def _sample_video_boxes(device, dtype, batch: int = 2, time: int = 3, n_boxes: int = 1) -> torch.Tensor:+ # Clockwise vertices_plus corners for a 3x3 box starting at (1, 1).+ frame = torch.tensor(+ [[[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0]]],+ device=device,+ dtype=dtype,+ ) # (1, 4, 2)+ return frame.view(1, 1, 1, 4, 2).expand(batch, time, n_boxes, 4, 2).contiguous().clone()++ def test_smoke(self, device, dtype):+ boxes = self._sample_video_boxes(device, dtype)+ video_boxes = VideoBoxes.from_tensor(boxes)+ assert isinstance(video_boxes, VideoBoxes)+ assert video_boxes.temporal_channel_size == boxes.size(1)++ def test_exception(self, device, dtype):+ frame = self._sample_video_boxes(device, dtype, batch=1, time=1)[0] # (T, N, 4, 2)+ with pytest.raises(ValueError):+ VideoBoxes.from_tensor(frame)+ with pytest.raises(ValueError):+ VideoBoxes.from_tensor([self._sample_video_boxes(device, dtype)])++ def test_cardinality(self, device, dtype):+ boxes = self._sample_video_boxes(device, dtype, batch=2, time=3, n_boxes=2)+ video_boxes = VideoBoxes.from_tensor(boxes)+ assert video_boxes.data.shape == (boxes.size(0) * boxes.size(1), boxes.size(2), 4, 2)+ out = video_boxes.to_tensor()+ assert isinstance(out, torch.Tensor)+ assert out.shape == boxes.shape++ def test_roundtrip_and_clone(self, device, dtype):+ boxes = self._sample_video_boxes(device, dtype)+ video_boxes = VideoBoxes.from_tensor(boxes)+ restored = video_boxes.to_tensor()+ assert isinstance(restored, torch.Tensor)+ self.assert_close(restored, boxes)++ cloned = video_boxes.clone()+ assert isinstance(cloned, VideoBoxes)+ assert cloned is not video_boxes+ assert cloned.temporal_channel_size == video_boxes.temporal_channel_size+ self.assert_close(cloned.data, video_boxes.data)+ cloned.data[0, 0, 0, 0] = -1+ assert not torch.equal(cloned.data, video_boxes.data)++ def test_public_api_surface(self):+ # Pin #4016: VideoBoxes is exported and the overrides are documented.+ assert "VideoBoxes" in boxes_module.__all__+ assert VideoBoxes.__doc__ is not None+ for name in ("from_tensor", "to_tensor", "clone"):+ assert getattr(VideoBoxes, name).__doc__ is not None++ def test_gradcheck(self, device):+ boxes = self._sample_video_boxes(device, torch.float64)++ def _wrap(x: torch.Tensor) -> torch.Tensor:+ return VideoBoxes.from_tensor(x).to_tensor() # type: ignore[return-value]++ self.gradcheck(_wrap, (boxes,))