Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): validate nms box shape (#4121)

Apoorv Darshan6862761e121e
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index e83ddae28..a4482e6f2 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -556,7 +556,7 @@ def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torc
tensor([0, 3, 1])
"""
- if len(boxes.shape) != 2 and boxes.shape[-1] != 4:
+ if boxes.ndim != 2 or boxes.shape[-1] != 4:
raise ValueError(f"boxes expected as Nx4. Got: {boxes.shape}.")
if len(scores.shape) != 1:
diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.py
index ab6541030..b17a71020 100644
--- a/tests/geometry/test_bbox.py
+++ b/tests/geometry/test_bbox.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import pytest
import torch
import kornia
@@ -320,3 +321,17 @@ class TestNMS(BaseTester):
expected = torch.tensor([0, 3, 1], device=device, dtype=torch.long)
actual = nms(boxes, scores, iou_threshold=0.8)
self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize(
+ ("boxes_shape", "scores_shape"),
+ [
+ ((3, 5), (3,)),
+ ((2, 3, 4), (2,)),
+ ],
+ )
+ def test_invalid_boxes_shape(self, boxes_shape, scores_shape, device, dtype):
+ boxes = torch.zeros(boxes_shape, device=device, dtype=dtype)
+ scores = torch.zeros(scores_shape, device=device, dtype=dtype)
+
+ with pytest.raises(ValueError, match="boxes expected as Nx4"):
+ nms(boxes, scores, iou_threshold=0.8)