Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix Boxes.from_tensor(boxes, mode="vertices") (#1740)

hal-3141124855c279d
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index bbc005ec3..79d14342b 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -97,10 +97,15 @@ def _boxes_to_quadrilaterals(
if mode.startswith("vertices"):
if mode == "vertices":
- # Avoid passing reference
quadrilaterals = boxes.clone()
+ # Here, vertices are quadrilaterals with width and height defined as `width = xmax - xmin` and
+ # `height = ymax - ymin`. We need to convert to `width = xmax - xmin + 1` and `height = ymax - ymin + 1` to
+ # match with internal Boxes Kornia representation.
+ quadrilaterals[..., 1:3, 0] = quadrilaterals[..., 1:3, 0] - 1
+ quadrilaterals[..., 2:, 1] = quadrilaterals[..., 2:, 1] - 1
elif mode == "vertices_plus":
- quadrilaterals = boxes.clone() # TODO: perform +1
+ # Avoid passing reference
+ quadrilaterals = boxes.clone()
else:
raise ValueError(f"Unknown mode {mode}")
validate_boxes or validate_bbox(quadrilaterals)
diff --git a/test/geometry/test_boxes.py b/test/geometry/test_boxes.py
index a7446ad57..b9053de70 100644
--- a/test/geometry/test_boxes.py
+++ b/test/geometry/test_boxes.py
@@ -84,12 +84,18 @@ class TestBoxes2D:
box_xyxy = torch.as_tensor([[1, 2, 3, 4]], device=device, dtype=dtype).view(*shape)
box_xyxy_plus = torch.as_tensor([[1, 2, 2, 3]], device=device, dtype=dtype).view(*shape)
box_xywh = torch.as_tensor([[1, 2, 2, 2]], device=device, dtype=dtype).view(*shape)
+ box_vertices = torch.as_tensor([[[1, 2], [3, 2], [3, 4], [1, 4]]], device=device, dtype=dtype).view(*shape, 2)
+ box_vertices_plus = torch.as_tensor([[[1, 2], [2, 2], [2, 3], [1, 3]]], device=device, dtype=dtype).view(
+ *shape, 2
+ )
expected_box = torch.as_tensor([[[1, 2], [2, 2], [2, 3], [1, 3]]], device=device, dtype=dtype).view(*shape, 2)
boxes_xyxy = Boxes.from_tensor(box_xyxy, mode='xyxy').data
boxes_xyxy_plus = Boxes.from_tensor(box_xyxy_plus, mode='xyxy_plus').data
boxes_xywh = Boxes.from_tensor(box_xywh, mode='xywh').data
+ box_vertices = Boxes.from_tensor(box_vertices, mode='vertices').data
+ boxes_vertices_plus = Boxes.from_tensor(box_vertices_plus, mode='vertices_plus').data
assert boxes_xyxy.shape == expected_box.shape
assert_allclose(boxes_xyxy, expected_box)
@@ -100,6 +106,12 @@ class TestBoxes2D:
assert boxes_xywh.shape == expected_box.shape
assert_allclose(boxes_xywh, expected_box)
+ assert box_vertices.shape == expected_box.shape
+ assert_allclose(box_vertices, expected_box)
+
+ assert boxes_vertices_plus.shape == expected_box.shape
+ assert_allclose(boxes_vertices_plus, expected_box)
+
@pytest.mark.parametrize('shape', [(1, 4), (1, 1, 4)])
def test_from_invalid_tensor(self, shape: Tuple[int], device, dtype):
box_xyxy = torch.as_tensor([[1, 2, -3, 4]], device=device, dtype=dtype).view(*shape) # Invalid width