Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix Boxes.from_tensor crash on nested numeric lists (#4896)

Mohammad Hijjawi5f82ff6b0eb1
diff --git a/changelog.d/4896.fixed.md b/changelog.d/4896.fixed.md
new file mode 100644
index 000000000..8e0ab0701
--- /dev/null
+++ b/changelog.d/4896.fixed.md
@@ -0,0 +1 @@
+`Boxes.from_tensor` accepts nested numeric lists shaped like `(N, 4)` and an empty Python list instead of raising `AttributeError` / `ValueError`.
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 2bf101a47..1ea291144 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -629,16 +629,15 @@ class Boxes:
return area.view(self._data.shape[:2]) if self._data.ndim == 4 else area
@classmethod
- def from_tensor(
- cls, boxes: torch.Tensor | list[torch.Tensor], mode: str = "xyxy", validate_boxes: bool = True
- ) -> Boxes:
+ def from_tensor(cls, boxes: torch.Tensor | list, mode: str = "xyxy", validate_boxes: bool = True) -> Boxes:
r"""Create :class:`Boxes` from boxes stored in another format.
See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.
Args:
boxes: 2D boxes, shape of :math:`(N, 4)`, :math:`(B, N, 4)`, :math:`(N, 4, 2)` or
- :math:`(B, N, 4, 2)`, or a list of :math:`(N, 4)` or :math:`(N, 4, 2)` tensors matching ``mode``.
+ :math:`(B, N, 4, 2)`, a nested numeric list with one of those shapes, or a list of
+ :math:`(N, 4)` or :math:`(N, 4, 2)` tensors matching ``mode``.
mode: The format in which the boxes are provided:
* 'xyxy': ``xmin, ymin, xmax, ymax`` with exclusive extent. With shape :math:`(N, 4)`,
@@ -678,8 +677,15 @@ class Boxes:
quadrilaterals: torch.Tensor | list[torch.Tensor]
if isinstance(boxes, torch.Tensor):
quadrilaterals = _boxes_to_quadrilaterals(boxes, mode=mode, validate_boxes=validate_boxes)
- else:
+ elif len(boxes) == 0:
+ # An empty list holds no boxes, like an empty (0, 4) or (0, 4, 2) tensor; converting one checks ``mode``.
+ empty = torch.zeros(0, 4, 2) if mode.lower().startswith("vertices") else torch.zeros(0, 4)
+ quadrilaterals = _boxes_to_quadrilaterals(empty, mode=mode, validate_boxes=validate_boxes)
+ elif isinstance(boxes[0], torch.Tensor):
quadrilaterals = [_boxes_to_quadrilaterals(box, mode, validate_boxes) for box in boxes]
+ else:
+ # A nested numeric list converts as the tensor it spells.
+ quadrilaterals = _boxes_to_quadrilaterals(torch.as_tensor(boxes), mode=mode, validate_boxes=validate_boxes)
return cls(quadrilaterals, False, mode)
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index a5f4212cf..38d1d9ec4 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -381,6 +381,37 @@ class TestBoxes2D(BaseTester):
assert boxes_vertices_plus.shape == expected_box.shape
self.assert_close(boxes_vertices_plus, expected_box)
+ @pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh", "vertices", "vertices_plus"])
+ @pytest.mark.parametrize("batched", [False, True])
+ def test_from_tensor_accepts_nested_numeric_list(self, mode, batched, device, dtype):
+ """A nested Python list converts like the tensor it spells, in every mode."""
+ rows = [[1.0, 2.0, 5.0, 4.0], [6.0, 3.0, 9.0, 8.0]]
+ if mode.startswith("vertices"):
+ rows = Boxes.from_tensor(torch.tensor(rows), mode="xyxy").to_tensor(mode).tolist()
+ if batched:
+ rows = [rows]
+ boxes = Boxes.from_tensor(rows, mode=mode)
+ expected = Boxes.from_tensor(torch.tensor(rows, device=device, dtype=dtype), mode=mode)
+ assert boxes.data.shape == expected.data.shape
+ self.assert_close(boxes.data.to(device=device, dtype=dtype), expected.data)
+ self.assert_close(boxes.to_tensor(mode).to(device=device, dtype=dtype), expected.to_tensor(mode))
+
+ def test_from_tensor_nested_numeric_list_honours_validate_boxes(self):
+ with pytest.raises(ValueError, match="negative widths"):
+ Boxes.from_tensor([[1.0, 2.0, -3.0, 4.0]], mode="xyxy")
+ assert Boxes.from_tensor([[1.0, 2.0, -3.0, 4.0]], mode="xyxy", validate_boxes=False).data.shape == (1, 4, 2)
+
+ @pytest.mark.parametrize("mode", ["xyxy", "xywh", "vertices"])
+ def test_from_tensor_accepts_empty_list(self, mode):
+ """An empty Python list yields an empty boxes tensor, as an empty (0, 4) tensor does."""
+ boxes = Boxes.from_tensor([], mode=mode)
+ assert boxes.data.shape == (0, 4, 2)
+ assert boxes.to_tensor("xyxy").shape == (0, 4)
+
+ def test_from_tensor_empty_list_checks_mode(self):
+ with pytest.raises(ValueError, match="Unknown mode"):
+ Boxes.from_tensor([], mode="bogus")
+
@pytest.mark.parametrize("shape", [(1, 4), (1, 1, 4)])
def test_from_invalid_tensor(self, shape, device, dtype):
box_xyxy = torch.as_tensor([[1, 2, -3, 4]], device=device, dtype=dtype).view(*shape) # Invalid width