Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix Boxes.merge list padding metadata (#4216)

Abyss Lab1dcae7a54389
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d5ddcf1b..e50a6f0d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -289,10 +289,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
for unbatched `(N, 4, 2)` input. The old `dim=1` was correct for batched
`(B, N, 4, 2)` data (where dim 1 is the box axis) but wrong for 3-D tensors
(where dim 1 is the vertex dimension); `dim=-3` is correct in both cases and
- the behaviour of the batched path is byte-identical. Also clear the stale
- ``_N`` list-padding metadata on both the inplace and non-inplace paths after
- every merge so that ``to_tensor`` counts the merged boxes correctly instead of
- silently truncating them (#4168).
+ the behaviour of the batched path is byte-identical. For list-backed inputs,
+ each batch row is now repacked with its real boxes before all trailing padding,
+ and the combined per-image padding counts are retained. This makes ``to_tensor``
+ trim only padding instead of dropping merged boxes or exposing old padding as
+ real boxes (#4168, #4175).
* `Boxes3D.to_tensor` and `Boxes3D.get_boxes_shape` are differentiable again (#1396). Both reduce a box's 8
vertices to its min/max corner with `amin`/`amax`, which is a genuine kink -- not differentiable in the
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 954f15d3a..c08d8953e 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -246,9 +246,9 @@ class Boxes:
or rejected by its first box alone and the remaining boxes are cast to that dtype. For a single tensor,
:meth:`from_tensor` silently casts integer input to ``float32``. For a list, it converts each element
independently and then pads into the first converted element's dtype, recasting the remaining elements.
- - :meth:`merge` concatenates batched boxes along the box axis, while :meth:`index_put` replaces selected
- coordinates. Both methods are non-mutating by default. :meth:`merge` is currently unsafe for unbatched
- and list-backed objects because it respectively concatenates vertices and preserves stale padding metadata.
+ - :meth:`merge` concatenates boxes along the box axis and repacks list-backed batch rows so their padding
+ remains at the end, while :meth:`index_put` replaces selected coordinates. Both methods are non-mutating
+ by default.
.. warning::
The inclusive ``+1`` arithmetic differs from torchvision, COCO, and albumentations and is tracked as a
@@ -259,10 +259,8 @@ class Boxes:
:func:`~kornia.geometry.bbox.nms` convention is
`#4008 <https://github.com/kornia/kornia/issues/4008>`_. The differing ``width``/``height`` argument order
of :func:`~kornia.geometry.bbox.bbox_to_mask` and :meth:`to_mask` is tracked in
- `#4014 <https://github.com/kornia/kornia/issues/4014>`_. Unbatched and list-backed :meth:`merge` are tracked
- in `#4168 <https://github.com/kornia/kornia/issues/4168>`_ and
- `#4175 <https://github.com/kornia/kornia/issues/4175>`_, respectively. The integer-input policy split
- between the constructor and :meth:`from_tensor` is
+ `#4014 <https://github.com/kornia/kornia/issues/4014>`_. The integer-input policy split between the
+ constructor and :meth:`from_tensor` is
`#4012 <https://github.com/kornia/kornia/issues/4012>`_. With ``validate_boxes=True``, vertex modes remain
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>`_.
@@ -360,20 +358,45 @@ class Boxes:
inplace: do transform in-place and return self.
Note:
- Any list-padding metadata (``_N``) is cleared after the merge because
- the merged tensor has a new total box count that is incompatible with
- the original per-image lengths recorded before the merge.
+ When either input was created from a list, each batch row is repacked
+ so that its real boxes precede all trailing padding. The merged object
+ keeps the combined per-image padding counts in ``_N``.
"""
- data = torch.cat([self._data, boxes.data], dim=-3)
+ padding: Optional[list[int]] = None
+ if self._N is not None or boxes._N is not None:
+ if self._data.shape[0] != boxes.data.shape[0]:
+ raise ValueError(
+ f"Batch size mismatch. Got {self._data.shape[0]} for self and {boxes.data.shape[0]} for boxes."
+ )
+
+ self_padding = self._N if self._N is not None else [0] * self._data.shape[0]
+ boxes_padding = boxes._N if boxes._N is not None else [0] * boxes.data.shape[0]
+ data = torch.stack(
+ [
+ torch.cat(
+ [
+ self._data[i, : self._data.shape[-3] - self_pad],
+ boxes.data[i, : boxes.data.shape[-3] - boxes_pad],
+ self._data[i, self._data.shape[-3] - self_pad :],
+ boxes.data[i, boxes.data.shape[-3] - boxes_pad :],
+ ]
+ )
+ for i, (self_pad, boxes_pad) in enumerate(zip(self_padding, boxes_padding))
+ ]
+ )
+ padding = [self_pad + boxes_pad for self_pad, boxes_pad in zip(self_padding, boxes_padding)]
+ else:
+ data = torch.cat([self._data, boxes.data], dim=-3)
+
if inplace:
self._data = data
- self._N = None
+ self._N = padding
return self
obj = self.clone()
obj._data = data
- obj._N = None
+ obj._N = padding
return obj
def index_put(
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 5276d94a2..dd49e15ed 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -524,7 +524,7 @@ class TestBoxes2D(BaseTester):
assert a2.data.shape == (2, 4, 2)
self.assert_close(a2.to_tensor("xyxy"), expected_unbatched)
- # --- _N is cleared: to_tensor must not drop merged boxes ---
+ # --- List padding is moved behind merged boxes and remains metadata ---
# Build from a list so that _N is set (variable-length list padding).
# from_tensor with a list of (N, 4) tensors of different lengths produces a
# batched (B, max_N, 4, 2) tensor with _N recording per-batch padding.
@@ -540,7 +540,48 @@ class TestBoxes2D(BaseTester):
mode="xyxy",
)
merged_list = list_boxes.merge(extra_batched)
- assert merged_list._N is None, "_N must be None after merge"
+ assert merged_list._N == [1, 0]
+ merged_tensors = merged_list.to_tensor("xyxy")
+ assert isinstance(merged_tensors, list)
+ extra_tensors = extra_batched.to_tensor("xyxy")
+ assert isinstance(extra_tensors, torch.Tensor)
+ self.assert_close(merged_tensors[0], torch.cat([src1, extra_tensors[0]]))
+ self.assert_close(merged_tensors[1], torch.cat([src2, extra_tensors[1]]))
+
+ # Both operands may be list-backed, so their per-row padding counts must be combined.
+ other_list = Boxes.from_tensor(
+ [
+ torch.tensor([[6.0, 3.0, 9.0, 8.0], [0.0, 0.0, 3.0, 3.0]], device=device, dtype=dtype),
+ torch.tensor([[4.0, 4.0, 7.0, 7.0]], device=device, dtype=dtype),
+ ],
+ mode="xyxy",
+ )
+ other_tensors = other_list.to_tensor("xyxy")
+ assert isinstance(other_tensors, list)
+ expected_list = [torch.cat([src1, other_tensors[0]]), torch.cat([src2, other_tensors[1]])]
+
+ merged_lists = list_boxes.merge(other_list)
+ assert merged_lists._N == [1, 1]
+ actual_list = merged_lists.to_tensor("xyxy")
+ assert isinstance(actual_list, list)
+ for actual, expected in zip(actual_list, expected_list):
+ self.assert_close(actual, expected)
+
+ # The dense operand may also be on the left of a list-backed operand.
+ dense_first = extra_batched.merge(other_list)
+ assert dense_first._N == [0, 1]
+ actual_dense_first = dense_first.to_tensor("xyxy")
+ assert isinstance(actual_dense_first, list)
+ for dense_row, other_row, actual in zip(extra_tensors, other_tensors, actual_dense_first):
+ self.assert_close(actual, torch.cat([dense_row, other_row]))
+
+ result = list_boxes.merge(other_list, inplace=True)
+ assert result is list_boxes
+ assert list_boxes._N == [1, 1]
+ actual_inplace = list_boxes.to_tensor("xyxy")
+ assert isinstance(actual_inplace, list)
+ for actual, expected in zip(actual_inplace, expected_list):
+ self.assert_close(actual, expected)
def test_compute_area(self):