Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): support unbatched boxes in Boxes.pad, unpad and clamp (#4372)

abhijeet sharmaa7e2db6bef04
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 189d56d7f..49cf7182f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -394,7 +394,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* `depth_to_normals` now raises `ShapeError` when `H < 2` or `W < 2`, since surface normals need two
tangent directions. Previously, singleton axes could yield zero or non-finite normals, and empty
spatial dimensions failed inside padding. Inputs with both dimensions at least 2 are unchanged. (#4458)
-
+* `Boxes.pad`, `Boxes.unpad` and `Boxes.clamp` accept the unbatched `(N, 4, 2)` container the class
+ documents and constructs. All three assumed the batched `(B, N, 4, 2)` indexing: `pad` and `unpad`
+ broadcast the padding as `(B, 1, 1)`, which does not fit the unbatched `(N, 4)` coordinate view and
+ raised `RuntimeError: output with shape [1, 4] doesn't match the broadcast shape [1, 1, 4]`, and `clamp`
+ materialized its bounds with `repeat(1, _data.size(1), 4)` and raised `IndexError: too many indices for
+ tensor of dimension 2`. Adding a leading singleton batch axis to the same boxes made all three work.
+ They now broadcast against whichever rank the container holds and match the singleton-batch result;
+ an unbatched container carries one image, so a per-image tensor with more than one row is rejected.
+ Batched results are byte-identical, including for a non-finite bound: `clamp` stays comparison-based, so
+ a `NaN` bound leaves the coordinate alone rather than propagating into it (closes #4244). (#4372)
* `RandAugment`'s `m` guard is exclusive at both ends, but its docstring and its error message
both named the closed interval `[0, 30]`, so a user who asked for the maximum strength the
message advertised got an exception saying `30` was in range. Both now read `(0, 30)`; the
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 055b147db..c94a2032c 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -267,9 +267,7 @@ class Boxes:
unvalidated, and ``'vertices'`` also subtracts one from fixed vertex positions, potentially deforming the
input rather than rejecting it; this is tracked in `#4177 <https://github.com/kornia/kornia/issues/4177>`_.
The unimplemented ``trim``, ``translate(method='fast')``, and tuple-bound ``clamp`` paths are tracked in
- `#4017 <https://github.com/kornia/kornia/issues/4017>`_. The pad, unpad, and clamp operations fail for
- unbatched containers even though the class accepts :math:`(N, 4, 2)` data; this is tracked in
- `#4244 <https://github.com/kornia/kornia/issues/4244>`_.
+ `#4017 <https://github.com/kornia/kornia/issues/4017>`_.
"""
@@ -449,6 +447,22 @@ class Boxes:
obj._data = _data
return obj
+ def _broadcast_over_vertices(self, values: torch.Tensor) -> torch.Tensor:
+ """Shape a per-image ``(B, k)`` column so it broadcasts over ``self._data[..., i]``.
+
+ The batched container indexes as ``(B, N, 4)``, so the column needs one axis for the box
+ count. The unbatched ``(N, 4, 2)`` form carries a single implicit image and indexes as
+ ``(N, 4)``, so its ``(1, k)`` column already broadcasts and must not gain that axis.
+ """
+ if self._is_batched:
+ return values[..., None, :]
+ if values.size(0) != 1:
+ raise RuntimeError(
+ f"Unbatched (N, 4, 2) boxes carry a single image, so a per-image tensor must have one row. "
+ f"Got {values.size(0)}."
+ )
+ return values
+
def pad(self, padding_size: torch.Tensor) -> Boxes:
"""Pad every box in place.
@@ -456,22 +470,28 @@ class Boxes:
``padding_size`` is ordered as ``(left, right, top, bottom)``. Only
``left`` and ``top`` change the coordinate origin; this method returns
- ``self`` after adding those two values to every vertex. This operation
- supports only batched :math:`(B, N, 4, 2)` containers.
+ ``self`` after adding those two values to every vertex. Both the batched
+ :math:`(B, N, 4, 2)` and the unbatched :math:`(N, 4, 2)` container are
+ supported; the unbatched form carries a single image, so ``padding_size``
+ must have exactly one row.
Note:
- Padded :class:`~kornia.augmentation.RandomCrop` uses this method
- and therefore requires batched boxes.
+ Padded :class:`~kornia.augmentation.RandomCrop` routes bounding boxes
+ through this method, and so accepts either container: a rank-3
+ :math:`(B, N, 4)` ``bbox`` builds a batched one, and a rank-2
+ :math:`(N, 4)` ``bbox`` for a single image builds an unbatched one.
Args:
padding_size: Per-batch padding in ``(left, right, top, bottom)``
- order, shaped :math:`(B, 4)`.
+ order, shaped :math:`(B, 4)`. A single row broadcasts across the
+ batch.
"""
if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
- self._data[..., 0] += padding_size[..., None, :1].to(device=self._data.device) # left padding
- self._data[..., 1] += padding_size[..., None, 2:3].to(device=self._data.device) # top padding
+ offset = padding_size.to(device=self._data.device)
+ self._data[..., 0] += self._broadcast_over_vertices(offset[..., :1]) # left padding
+ self._data[..., 1] += self._broadcast_over_vertices(offset[..., 2:3]) # top padding
return self
def unpad(self, padding_size: torch.Tensor) -> Boxes:
@@ -481,18 +501,22 @@ class Boxes:
``padding_size`` is ordered as ``(left, right, top, bottom)``. Only
``left`` and ``top`` change the coordinate origin; this method returns
- ``self`` after subtracting those two values from every vertex. This
- operation supports only batched :math:`(B, N, 4, 2)` containers.
+ ``self`` after subtracting those two values from every vertex. Both the
+ batched :math:`(B, N, 4, 2)` and the unbatched :math:`(N, 4, 2)` container
+ are supported; the unbatched form carries a single image, so
+ ``padding_size`` must have exactly one row.
Args:
padding_size: Per-batch padding in ``(left, right, top, bottom)``
- order, shaped :math:`(B, 4)`.
+ order, shaped :math:`(B, 4)`. A single row broadcasts across the
+ batch.
"""
if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
- self._data[..., 0] -= padding_size[..., None, :1].to(device=self._data.device) # left padding
- self._data[..., 1] -= padding_size[..., None, 2:3].to(device=self._data.device) # top padding
+ offset = padding_size.to(device=self._data.device)
+ self._data[..., 0] -= self._broadcast_over_vertices(offset[..., :1]) # left padding
+ self._data[..., 1] -= self._broadcast_over_vertices(offset[..., 2:3]) # top padding
return self
def clamp(
@@ -506,21 +530,26 @@ class Boxes:
See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.
Convention:
- Bounds must be tensors with one ``(x, y)`` pair per batch element.
+ Bounds must be tensors with one ``(x, y)`` pair per batch element,
+ or a single row that broadcasts across the batch.
Every vertex is clamped independently, so a box wholly outside the
bounds collapses onto the nearest boundary instead of being removed.
- This operation supports only batched :math:`(B, N, 4, 2)` containers.
+ Both the batched :math:`(B, N, 4, 2)` and the unbatched
+ :math:`(N, 4, 2)` container are supported; the unbatched form carries
+ a single image, so the bounds must have exactly one row.
Coordinates below ``topleft`` are raised to the lower bound and
coordinates above ``botright`` are lowered to the upper bound. The
implementation accepts only tensor bounds with one ``(x, y)`` pair per
- batch element.
+ batch element, or a single row that broadcasts across the batch.
Args:
topleft: Tensor of shape :math:`(B, 2)` containing the minimum
- ``x`` and ``y`` coordinate allowed for each batch item.
+ ``x`` and ``y`` coordinate allowed for each batch item. A single
+ row broadcasts across the batch.
botright: Tensor of shape :math:`(B, 2)` containing the maximum
- ``x`` and ``y`` coordinate allowed for each batch item.
+ ``x`` and ``y`` coordinate allowed for each batch item. A single
+ row broadcasts across the batch.
inplace: If ``True``, clamp this object in place. Otherwise, return
a new :class:`Boxes` object with clamped data.
@@ -534,17 +563,23 @@ class Boxes:
_data = self._data
else:
_data = self._data.clone()
- topleft_x = topleft[:, None, :1].repeat(1, _data.size(1), 4)
- _data[..., 0][_data[..., 0] < topleft_x] = topleft_x[_data[..., 0] < topleft_x]
-
- topleft_y = topleft[:, None, 1:].repeat(1, _data.size(1), 4)
- _data[..., 1][_data[..., 1] < topleft_y] = topleft_y[_data[..., 1] < topleft_y]
-
- botright_x = botright[:, None, :1].repeat(1, _data.size(1), 4)
- _data[..., 0][_data[..., 0] > botright_x] = botright_x[_data[..., 0] > botright_x]
-
- botright_y = botright[:, None, 1:].repeat(1, _data.size(1), 4)
- _data[..., 1][_data[..., 1] > botright_y] = botright_y[_data[..., 1] > botright_y]
+ # Broadcast the per-image bounds rather than materialising them at the data's shape: the
+ # masked assignment this replaces needed a bound tensor of exactly the mask's shape, which
+ # is what tied it to the batched (B, N, 4) indexing. ``torch.where`` on the same comparison
+ # keeps its semantics exactly, which ``maximum``/``minimum`` would not: every comparison
+ # against a NaN bound is False, so the coordinate is left alone instead of becoming NaN.
+ topleft_x = self._broadcast_over_vertices(topleft[..., :1])
+ topleft_y = self._broadcast_over_vertices(topleft[..., 1:])
+ botright_x = self._broadcast_over_vertices(botright[..., :1])
+ botright_y = self._broadcast_over_vertices(botright[..., 1:])
+
+ coord_x, coord_y = _data[..., 0], _data[..., 1]
+ coord_x = torch.where(coord_x < topleft_x, topleft_x.expand_as(coord_x), coord_x)
+ coord_y = torch.where(coord_y < topleft_y, topleft_y.expand_as(coord_y), coord_y)
+ coord_x = torch.where(coord_x > botright_x, botright_x.expand_as(coord_x), coord_x)
+ coord_y = torch.where(coord_y > botright_y, botright_y.expand_as(coord_y), coord_y)
+ _data[..., 0] = coord_x
+ _data[..., 1] = coord_y
if inplace:
return self
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 957c47396..6aae5536c 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -171,6 +171,41 @@ class TestAugmentationSequential:
reproducibility_test((input, bbox), aug)
+ @pytest.mark.parametrize("num_boxes", [1, 2])
+ def test_convention_padded_random_crop_accepts_rank2_bboxes_4244(self, num_boxes, device, dtype):
+ # kornia#4244: RandomCrop's padded path routes bounding boxes through Boxes.pad and
+ # Boxes.unpad. A rank-2 (N, 4) bbox for a single image builds an *unbatched* Boxes
+ # container, which those methods crashed on with "output with shape [1, 4] doesn't match
+ # the broadcast shape [1, 1, 4]". This is the reproducer from the issue's follow-up, and it
+ # is the only public route to that container: a rank-3 (B, N, 4) bbox builds a batched one,
+ # which never crashed. Both box counts are covered because clamp failed differently at N=1
+ # (IndexError) and N=2 (RuntimeError) on the unbatched path.
+ input = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
+ bbox = torch.tensor([[1.0, 1.0, 4.0, 4.0], [2.0, 2.0, 5.0, 6.0]], device=device, dtype=dtype)[:num_boxes]
+ aug = K.AugmentationSequential(K.RandomCrop((6, 6), padding=1, p=1.0), data_keys=["input", "bbox_xyxy"])
+
+ out_input, out_bbox = aug(input, bbox)
+
+ assert out_input.shape == (1, 3, 6, 6)
+ # the rank of the caller's bbox is preserved on the way out
+ assert out_bbox.shape == (num_boxes, 4)
+ assert torch.isfinite(out_bbox).all()
+
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ def test_padded_random_crop_batched_bboxes(self, batch_size, device, dtype):
+ # The batched (B, N, 4) companion of the pin above. It builds a batched Boxes container,
+ # which always worked, so it passes on either side of the fix and is kept only as a guard
+ # that the rank-2 repair did not disturb the batched route.
+ input = torch.rand(batch_size, 3, 8, 8, device=device, dtype=dtype)
+ bbox = torch.tensor([[[1.0, 1.0, 4.0, 4.0]]], device=device, dtype=dtype).expand(batch_size, -1, -1)
+ aug = K.AugmentationSequential(K.RandomCrop((6, 6), padding=1, p=1.0), data_keys=["input", "bbox_xyxy"])
+
+ out_input, out_bbox = aug(input, bbox)
+
+ assert out_input.shape == (batch_size, 3, 6, 6)
+ assert out_bbox.shape == (batch_size, 1, 4)
+ assert torch.isfinite(out_bbox).all()
+
def test_random_crops_and_flips(self, device, dtype):
width, height = 100, 100
crop_width, crop_height = 3, 3
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 474361104..90c0b71e8 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -784,31 +784,45 @@ class TestBoxes2D(BaseTester):
self.assert_close(boxes.data[:, :1], first, atol=0.0, rtol=0.0)
self.assert_close(boxes.data[:, 1:], torch.zeros_like(boxes.data[:, 1:]), atol=0.0, rtol=0.0)
- @pytest.mark.parametrize("operation, inplace", [("pad", None), ("unpad", None), ("clamp", False), ("clamp", True)])
- @pytest.mark.parametrize("num_boxes", [1, 2])
- def test_wart_unbatched_geometry_operations_raise_4244(self, operation, inplace, num_boxes, device, dtype):
- # Wart pin for kornia#4244: the documented unbatched (N, 4, 2) form
- # fails although its singleton-batched counterpart works. Clamp reaches
- # indexing failure for one box and broadcasting failure for two boxes.
- boxes = Boxes(_unbatched_geometry_data(device, dtype)[:num_boxes])
- if operation == "clamp":
- with pytest.raises((RuntimeError, IndexError)):
- boxes.clamp(
- torch.tensor([[2.0, 3.0]], device=device, dtype=dtype),
- torch.tensor([[6.0, 7.0]], device=device, dtype=dtype),
- inplace=inplace,
- )
+ @pytest.mark.parametrize("non_finite", [float("nan"), float("inf"), float("-inf")])
+ @pytest.mark.parametrize("bound", ["topleft", "botright"])
+ @pytest.mark.parametrize("position", [0, 1])
+ def test_convention_clamp_leaves_coordinates_alone_for_a_non_finite_bound_4244(
+ self, non_finite, bound, position, device, dtype
+ ):
+ # clamp is comparison-based: every comparison against a non-finite bound that is NaN is
+ # False, so the coordinate is left alone rather than taking the bound. maximum/minimum do
+ # not agree here -- they propagate the NaN into every coordinate on that axis -- which is
+ # why this pin exists alongside the rank fix that motivated rewriting the bound broadcast.
+ # An infinite bound is a real clamp on one side and a no-op on the other, so it is swept
+ # too, and both bound tensors and both coordinate positions are covered.
+ data = torch.tensor([[[[1.0, 2.0], [5.0, 2.0], [5.0, 4.0], [1.0, 4.0]]]], device=device, dtype=dtype)
+ topleft = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)
+ botright = torch.tensor([[10.0, 10.0]], device=device, dtype=dtype)
+ if bound == "topleft":
+ topleft[0, position] = non_finite
else:
- with pytest.raises((RuntimeError, IndexError)):
- getattr(boxes, operation)(torch.tensor([[10.0, 99.0, 20.0, 88.0]], device=device, dtype=dtype))
+ botright[0, position] = non_finite
+
+ out = Boxes(data.clone()).clamp(topleft, botright, inplace=False).data
+
+ # Hand-derived from the two ordered comparison passes, lower bound first:
+ # topleft=nan -> `c < nan` is False, so the coordinate is left alone
+ # topleft=+inf -> `c < inf` raises every coordinate to +inf, which the botright pass then
+ # lowers to botright (10), so +inf never survives
+ # topleft=-inf -> `c < -inf` is False, left alone
+ # botright=nan -> `c > nan` is False, left alone
+ # botright=+inf-> `c > inf` is False, left alone
+ # botright=-inf-> `c > -inf` lowers every coordinate to -inf
+ expected = data.clone()
+ if bound == "topleft" and non_finite == float("inf"):
+ expected[..., position] = botright[0, position]
+ elif bound == "botright" and non_finite == float("-inf"):
+ expected[..., position] = float("-inf")
+ self.assert_close(out, expected, atol=0.0, rtol=0.0)
@pytest.mark.parametrize("operation, inplace", [("pad", None), ("unpad", None), ("clamp", False), ("clamp", True)])
@pytest.mark.parametrize("num_boxes", [1, 2])
- @pytest.mark.xfail(
- strict=True,
- raises=(RuntimeError, IndexError),
- reason="kornia#4244: unbatched geometry operations do not match singleton batches",
- )
def test_convention_unbatched_geometry_operations_match_singleton_batch_4244(
self, operation, inplace, num_boxes, device, dtype
):
@@ -840,6 +854,30 @@ class TestBoxes2D(BaseTester):
assert actual is unbatched
self.assert_close(actual.data, expected.data.squeeze(0), atol=0.0, rtol=0.0)
+ @pytest.mark.parametrize("operation, inplace", [("pad", None), ("unpad", None), ("clamp", False), ("clamp", True)])
+ def test_single_row_broadcasts_across_batch(self, operation, inplace, device, dtype):
+ data = _unbatched_geometry_data(device, dtype)[:2]
+ batched = Boxes(torch.stack([data, data]))
+ if operation == "clamp":
+ limits_single = (
+ torch.tensor([[2.0, 3.0]], device=device, dtype=dtype),
+ torch.tensor([[6.0, 7.0]], device=device, dtype=dtype),
+ )
+ limits_full = (
+ torch.tensor([[2.0, 3.0], [2.0, 3.0]], device=device, dtype=dtype),
+ torch.tensor([[6.0, 7.0], [6.0, 7.0]], device=device, dtype=dtype),
+ )
+ expected = Boxes(batched.data.clone()).clamp(*limits_full, inplace=inplace)
+ actual = batched.clamp(*limits_single, inplace=inplace)
+ else:
+ padding_single = torch.tensor([[10.0, 99.0, 20.0, 88.0]], device=device, dtype=dtype)
+ padding_full = torch.tensor(
+ [[10.0, 99.0, 20.0, 88.0], [10.0, 99.0, 20.0, 88.0]], device=device, dtype=dtype
+ )
+ expected = getattr(Boxes(batched.data.clone()), operation)(padding_full)
+ actual = getattr(batched, operation)(padding_single)
+ self.assert_close(actual.data, expected.data, atol=0.0, rtol=0.0)
+
@pytest.mark.parametrize("batched", [False, True])
@pytest.mark.parametrize("inplace", [False, True])
def test_wart_transform_boxes_empty_copy_aliases_input_4020(self, batched, inplace, device, dtype):