Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry.boxes)!: restore temporal axis in VideoBoxes compute_area and to_mask (#5614) (#6245)

Vuln3rat0rd9e934b8672c
diff --git a/changelog.d/6245.breaking.md b/changelog.d/6245.breaking.md
new file mode 100644
index 000000000..5905827a4
--- /dev/null
+++ b/changelog.d/6245.breaking.md
@@ -0,0 +1 @@
+`VideoBoxes.compute_area` and `VideoBoxes.to_mask` now restore the temporal axis, returning tensors shaped `(B, T, N)` and `(B, T, N, height, width)` respectively instead of keeping the flattened internal storage shape `(B * T, ...)`. This makes them consistent with `VideoBoxes.get_boxes_shape` and `VideoBoxes.to_tensor`.
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index b47670d73..7dc8f8546 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -629,11 +629,12 @@ class Boxes:
out-of-range boxes replaced by zero coordinates.
"""
area = self.compute_area()
- keep = torch.ones_like(area, dtype=torch.bool)
+ area_flat = area.reshape(self._valid.shape)
+ keep = torch.ones_like(area_flat, dtype=torch.bool)
if min_area is not None:
- keep &= ~(area < min_area)
+ keep &= ~(area_flat < min_area)
if max_area is not None:
- keep &= ~(area > max_area)
+ keep &= ~(area_flat > max_area)
obj = self if inplace else self.clone()
obj._valid &= keep
if min_area is not None or max_area is not None:
@@ -1082,6 +1083,9 @@ 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 ``(B, T, N, 4)``).
+ - :meth:`compute_area` returns ``(B, T, N)`` areas, and :meth:`to_mask` returns
+ ``(B, T, N, height, width)`` masks. :attr:`~Boxes.shape` and :attr:`~Boxes.data` stay the flattened
+ storage ``(B * T, N, 4, 2)``.
- 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.
@@ -1212,6 +1216,35 @@ class VideoBoxes(Boxes):
obj.temporal_channel_size = self.temporal_channel_size
return obj
+ def compute_area(self) -> torch.Tensor:
+ r"""Compute polygon area with the shoelace formula with the temporal axis restored.
+
+ See the Convention block on :class:`~kornia.geometry.boxes.VideoBoxes`.
+
+ Returns:
+ Area for each box, shaped ``(B, T, N)``.
+ """
+ area = super().compute_area()
+ batch_size = self._data.shape[0] // self.temporal_channel_size
+ return area.reshape(batch_size, self.temporal_channel_size, *area.shape[1:])
+
+ def to_mask(self, height: int, width: int) -> torch.Tensor:
+ r"""Convert 2D video boxes to masks with the temporal axis restored.
+
+ See the Convention block on :class:`~kornia.geometry.boxes.VideoBoxes`.
+
+ Args:
+ height: height of the masked image/images.
+ width: width of the masked image/images.
+
+ Returns:
+ The output mask tensor, shaped ``(B, T, N, height, width)`` and dtype of
+ :func:`Boxes.dtype`.
+ """
+ mask = super().to_mask(height, width)
+ batch_size = self._data.shape[0] // self.temporal_channel_size
+ return mask.reshape(batch_size, self.temporal_channel_size, *mask.shape[1:])
+
class Boxes3D:
r"""3D boxes containing N or BxN boxes.
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 8af87ff6f..a2a27f04c 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -2320,7 +2320,7 @@ class TestVideoBoxes(BaseTester):
video[0] = filtered[1]
self.assert_close(video.to_tensor("xyxy")[:1], expected[:1])
assert video.to_tensor("xyxy")[1, :, 1].count_nonzero() > 0
- assert filtered.to_mask(5, 5)[:, 1].count_nonzero() == 0
+ assert filtered.to_mask(5, 5)[:, :, 1].count_nonzero() == 0
"""Public API and round-trip coverage for :class:`VideoBoxes` (#4016)."""
@@ -2419,7 +2419,7 @@ class TestVideoBoxes(BaseTester):
# 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"):
+ for name in ("from_tensor", "to_tensor", "clone", "compute_area", "to_mask"):
assert getattr(VideoBoxes, name).__doc__ is not None
def test_gradcheck(self, device):
@@ -2589,6 +2589,57 @@ class TestVideoBoxes(BaseTester):
mask = video_boxes.to_mask(4, 5)
except TypeError as error:
raise AssertionError(str(error)) from error
- # One extent per box, and the mask keeps the flattened-time convention (B*T, N, H, W).
+ # One extent per box, and both compute_area and to_mask restore the temporal axis.
assert heights.numel() == widths.numel() == 6
- assert mask.shape == (6, 1, 4, 5)
+ assert heights.shape == (2, 3, 1)
+ assert widths.shape == (2, 3, 1)
+ assert video_boxes.compute_area().shape == (2, 3, 1)
+ assert mask.shape == (2, 3, 1, 4, 5)
+
+ def test_compute_area_and_to_mask_restore_temporal_axis_5614(self, device, dtype):
+ # Issue #5614: compute_area and to_mask restore the temporal axis (B, T, N, ...).
+ boxes = self._sample_video_boxes(device, dtype, batch=2, time=3, n_boxes=2)
+ # A different box in every frame: frame t is t pixels wider, video b sits b pixels lower.
+ boxes[..., 1:3, 0] += torch.arange(3, device=device, dtype=dtype).view(1, 3, 1, 1)
+ boxes[..., 1] += torch.arange(2, device=device, dtype=dtype).view(2, 1, 1, 1)
+ video = VideoBoxes.from_tensor(boxes)
+ heights, widths = video.get_boxes_shape()
+ area = video.compute_area()
+ mask = video.to_mask(6, 8)
+
+ assert area.shape == (2, 3, 2)
+ expected_area = torch.tensor([4.0, 6.0, 8.0], device=device, dtype=dtype).view(1, 3, 1).expand(2, 3, 2)
+ self.assert_close(area, expected_area, atol=0.0, rtol=0.0)
+ assert mask.shape == (2, 3, 2, 6, 8)
+ assert mask.dtype == dtype
+ expected_mask = torch.zeros_like(mask)
+ for b in range(2):
+ for t in range(3):
+ expected_mask[b, t, :, 1 + b : 4 + b, 1 : 4 + t] = 1
+ self.assert_close(mask, expected_mask, atol=0.0, rtol=0.0)
+
+ # Sibling method combination no longer fails with mismatched shapes
+ ratio = area / (heights * widths)
+ assert ratio.shape == (2, 3, 2)
+
+ # filter_boxes_by_area correctly updates valid flags and zeroed coordinates
+ filtered = video.filter_boxes_by_area(min_area=100.0)
+ assert isinstance(filtered, VideoBoxes)
+ assert filtered.temporal_channel_size == 3
+ assert filtered.data.shape == video.data.shape
+ assert filtered.compute_area().shape == (2, 3, 2)
+ assert filtered.compute_area().count_nonzero() == 0
+
+ # A partial filter zeroes the first frame of every video (area 4) and keeps the others.
+ partial = video.filter_boxes_by_area(min_area=5.0)
+ assert partial.to_tensor("xyxy")[:, 0].count_nonzero() == 0
+ self.assert_close(partial.to_tensor("xyxy")[:, 1:], video.to_tensor("xyxy")[:, 1:], atol=0.0, rtol=0.0)
+
+ @pytest.mark.parametrize("shape", [(0, 3, 2), (2, 3, 0)])
+ def test_compute_area_and_to_mask_empty_batches_5614(self, shape, device, dtype):
+ boxes = self._sample_video_boxes(device, dtype, batch=shape[0], time=shape[1], n_boxes=shape[2])
+ video = VideoBoxes.from_tensor(boxes)
+ area = video.compute_area()
+ mask = video.to_mask(4, 5)
+ assert area.shape == (shape[0], shape[1], shape[2])
+ assert mask.shape == (shape[0], shape[1], shape[2], 4, 5)