Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix/4168 boxes merge (#4213)

Ali Naqvi8db1499a2850
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5947e57e8..a308a41b3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -241,6 +241,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* Constructing `ScaleSpaceDetector` with `compile_modules` no longer permanently mutates the process-global
`torch._dynamo.config.capture_dynamic_output_shape_ops` setting. (#4134)
+* Fix `Boxes.merge` concatenating along the vertex axis instead of the box axis
+ 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).
+
* `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
classical sense -- wherever multiple vertices exactly tie for an axis extremum. Every face of an
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 065a272e2..f325415a7 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -347,21 +347,33 @@ class Boxes:
See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.
- Say, current instance holds :math:`(B, N, 4, 2)` and the incoming boxes holds :math:`(B, M, 4, 2)`,
- the merge results in :math:`(B, N + M, 4, 2)`.
+ For batched boxes, if the current instance holds :math:`(B, N, 4, 2)` and
+ the incoming boxes holds :math:`(B, M, 4, 2)`, the merge results in
+ :math:`(B, N + M, 4, 2)`.
+
+ For unbatched boxes, if the current instance holds :math:`(N, 4, 2)` and
+ the incoming boxes holds :math:`(M, 4, 2)`, the merge results in
+ :math:`(N + M, 4, 2)`.
Args:
boxes: 2D 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.
+
"""
- data = torch.cat([self._data, boxes.data], dim=1)
+ data = torch.cat([self._data, boxes.data], dim=-3)
if inplace:
self._data = data
+ self._N = None
return self
obj = self.clone()
obj._data = data
+ obj._N = None
return obj
def index_put(
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index cf5f3d5b5..395be3361 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -486,7 +486,64 @@ class TestBoxes2D(BaseTester):
self.gradcheck(lambda x: Boxes.from_tensor(x, mode="xyxy_plus").data, (t_boxes_xyxy,))
self.gradcheck(lambda x: Boxes.from_tensor(x, mode="xywh").data, (t_boxes_xyxy1,))
+ def test_merge(self, device, dtype):
+ # --- Unbatched: (N, 4, 2) + (M, 4, 2) -> (N+M, 4, 2) ---
+ # On base (dim=1) this produced shape (1, 8, 2) and to_tensor("xyxy")
+ # returned the single union row [[1, 2, 9, 8]] instead of two rows.
+ a = Boxes.from_tensor(torch.tensor([[1.0, 2.0, 5.0, 4.0]], device=device, dtype=dtype), mode="xyxy")
+ b = Boxes.from_tensor(torch.tensor([[6.0, 3.0, 9.0, 8.0]], device=device, dtype=dtype), mode="xyxy")
+ m = a.merge(b)
+
+ assert m.data.shape == (2, 4, 2), f"Unbatched merge shape: expected (2, 4, 2), got {m.data.shape}"
+ expected_unbatched = torch.tensor([[1.0, 2.0, 5.0, 4.0], [6.0, 3.0, 9.0, 8.0]], device=device, dtype=dtype)
+ self.assert_close(m.to_tensor("xyxy"), expected_unbatched)
+
+ # --- Batched: (B, N, 4, 2) + (B, M, 4, 2) -> (B, N+M, 4, 2) ---
+ # Verify that dim=-3 leaves the batched axis unchanged.
+ a_b = Boxes.from_tensor(
+ torch.tensor([[[1.0, 2.0, 5.0, 4.0]], [[0.0, 0.0, 3.0, 3.0]]], device=device, dtype=dtype), mode="xyxy"
+ )
+ b_b = Boxes.from_tensor(
+ torch.tensor([[[6.0, 3.0, 9.0, 8.0]], [[4.0, 4.0, 7.0, 7.0]]], device=device, dtype=dtype), mode="xyxy"
+ )
+ m_b = a_b.merge(b_b)
+
+ assert m_b.data.shape == (2, 2, 4, 2), f"Batched merge shape: expected (2, 2, 4, 2), got {m_b.data.shape}"
+ expected_batched = torch.tensor(
+ [[[1.0, 2.0, 5.0, 4.0], [6.0, 3.0, 9.0, 8.0]], [[0.0, 0.0, 3.0, 3.0], [4.0, 4.0, 7.0, 7.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(m_b.to_tensor("xyxy"), expected_batched)
+
+ # --- Inplace path returns self and updates data ---
+ a2 = Boxes.from_tensor(torch.tensor([[1.0, 2.0, 5.0, 4.0]], device=device, dtype=dtype), mode="xyxy")
+ b2 = Boxes.from_tensor(torch.tensor([[6.0, 3.0, 9.0, 8.0]], device=device, dtype=dtype), mode="xyxy")
+ result = a2.merge(b2, inplace=True)
+ assert result is a2, "inplace=True must return self"
+ 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 ---
+ # 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.
+ src1 = torch.tensor([[1.0, 2.0, 5.0, 4.0]], device=device, dtype=dtype) # (1, 4) β€” 1 box
+ src2 = torch.tensor(
+ [[1.0, 2.0, 5.0, 4.0], [6.0, 3.0, 9.0, 8.0]], device=device, dtype=dtype
+ ) # (2, 4) β€” 2 boxes
+ list_boxes = Boxes.from_tensor([src1, src2], mode="xyxy")
+ assert list_boxes._N is not None, "Prerequisite: _N must be set for list-constructed Boxes"
+ # list_boxes is batched (B=2, max_N=2, 4, 2); extra must match batch dim B=2.
+ extra_batched = 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),
+ mode="xyxy",
+ )
+ merged_list = list_boxes.merge(extra_batched)
+ assert merged_list._N is None, "_N must be None after merge"
+
def test_compute_area(self):
+
# Rectangle
box_1 = [[0.0, 0.0], [100.0, 0.0], [100.0, 50.0], [0.0, 50.0]]
# Trapezoid