π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Revert "optimized nms_bbox 4.83x (483.5% speedup) (#3251)" (#3349)
Edgar Riba248f5c5da109
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.pyindex bff7b3a9c..3ccf620ee 100644--- a/kornia/geometry/bbox.py+++ b/kornia/geometry/bbox.py@@ -18,11 +18,11 @@from __future__ import annotationsimport warnings-from typing import List, Optional+from typing import Optionalimport torch-from kornia.core import arange+from kornia.core import arange, stack, wherefrom .linalg import transform_points@@ -533,12 +533,12 @@ def transform_bbox(def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torch.Tensor:- """Perform non-maxima suppression (NMS) on a tensor of bounding boxes according to the intersection-over-union.+ """Perform non-maxima suppression (NMS) on tensor of bounding boxes according to the intersection-over-union (IoU).Args:boxes: tensor containing the encoded bounding boxes with the shape :math:`(N, (x_1, y_1, x_2, y_2))`.- scores: tensor containing the scores associated with each bounding box with shape :math:`(N,)`.- iou_threshold: the threshold to discard the overlapping boxes.+ scores: tensor containing the scores associated to each bounding box with shape :math:`(N,)`.+ iou_threshold: the throshold to discard the overlapping boxes.Return:A tensor mask with the indices to keep from the input set of boxes and scores.@@ -552,54 +552,40 @@ def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torc>>> scores = torch.tensor([0.9, 0.8, 0.7, 0.9])>>> nms(boxes, scores, iou_threshold=0.8)tensor([0, 3, 1])+"""- if boxes.numel() == 0:- return torch.empty((0,), dtype=torch.long, device=boxes.device)- if boxes.dim() != 2 or boxes.size(1) != 4:+ if len(boxes.shape) != 2 and boxes.shape[-1] != 4:raise ValueError(f"boxes expected as Nx4. Got: {boxes.shape}.")- if scores.dim() != 1:++ if len(scores.shape) != 1:raise ValueError(f"scores expected as N. Got: {scores.shape}.")- if boxes.size(0) != scores.size(0):- raise ValueError(f"boxes and scores must have same shape. Got: {boxes.shape, scores.shape}.")- # sort descending- _, order = scores.sort(descending=True)- N = boxes.size(0)- x1 = boxes[:, 0]- y1 = boxes[:, 1]- x2 = boxes[:, 2]- y2 = boxes[:, 3]+ if boxes.shape[0] != scores.shape[0]:+ raise ValueError(f"boxes and scores mus have same shape. Got: {boxes.shape, scores.shape}.")+ x1, y1, x2, y2 = boxes.unbind(-1)areas = (x2 - x1) * (y2 - y1)- # compute pairwise IoU matrix (N x N) using broadcasting- xx1 = torch.maximum(x1.unsqueeze(1), x1.unsqueeze(0)) # (N,N)- yy1 = torch.maximum(y1.unsqueeze(1), y1.unsqueeze(0))- xx2 = torch.minimum(x2.unsqueeze(1), x2.unsqueeze(0))- yy2 = torch.minimum(y2.unsqueeze(1), y2.unsqueeze(0))-- w = torch.clamp(xx2 - xx1, min=0.0)- h = torch.clamp(yy2 - yy1, min=0.0)- inter = w * h-- unions = areas.unsqueeze(1) + areas.unsqueeze(0) - inter- # avoid dividing by 0- unions = torch.where(unions > 0, unions, torch.ones_like(unions))- iou_matrix = inter / unions-- # clear self-iou- iou_matrix.fill_diagonal_(0.0)-- keep: List[int] = []- suppressed = torch.zeros((N,), dtype=torch.bool, device=boxes.device)-- # iterate in order of descending score, but suppression is vectorized- for idx in order:- if suppressed[idx]:- continue- keep.append(int(idx.item()))- # suppress all boxes that have IoU > threshold with the chosen box- suppressed |= iou_matrix[idx] > iou_threshold-- # return kept indices as a tensor (in descending-score order)- return torch.tensor(keep, dtype=torch.long, device=boxes.device)+ _, order = scores.sort(descending=True)++ keep = []+ while order.shape[0] > 0:+ i = order[0]+ keep.append(i)+ xx1 = torch.max(x1[i], x1[order[1:]])+ yy1 = torch.max(y1[i], y1[order[1:]])+ xx2 = torch.min(x2[i], x2[order[1:]])+ yy2 = torch.min(y2[i], y2[order[1:]])++ w = torch.clamp(xx2 - xx1, min=0.0)+ h = torch.clamp(yy2 - yy1, min=0.0)+ inter = w * h+ ovr = inter / (areas[i] + areas[order[1:]] - inter)++ inds = where(ovr <= iou_threshold)[0]+ order = order[inds + 1]++ if len(keep) > 0:+ return stack(keep)++ return torch.tensor(keep)diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.pyindex cb24c5ffe..6a94452cf 100644--- a/tests/geometry/test_bbox.py+++ b/tests/geometry/test_bbox.py@@ -304,89 +304,3 @@ 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)-- def test_no_overlap(self, device, dtype):- boxes = torch.tensor(- [- [0, 0, 10, 10],- [20, 20, 30, 30],- [40, 40, 50, 50],- ],- device=device,- dtype=dtype,- )- scores = torch.tensor([0.9, 0.8, 0.7], device=device, dtype=dtype)- expected = torch.tensor([0, 1, 2], device=device, dtype=torch.long)- actual = nms(boxes, scores, iou_threshold=0.5)- self.assert_close(actual, expected)-- def test_complete_overlap(self, device, dtype):- boxes = torch.tensor(- [- [0, 0, 10, 10],- [0, 0, 10, 10],- [0, 0, 10, 10],- ],- device=device,- dtype=dtype,- )- scores = torch.tensor([0.5, 0.9, 0.7], device=device, dtype=dtype)- # Highest score (idx=1) kept, others removed- expected = torch.tensor([1], device=device, dtype=torch.long)- actual = nms(boxes, scores, iou_threshold=0.5)- self.assert_close(actual, expected)-- def test_empty_input(self, device, dtype):- boxes = torch.empty((0, 4), device=device, dtype=dtype)- scores = torch.empty((0,), device=device, dtype=dtype)- expected = torch.empty((0,), device=device, dtype=torch.long)- actual = nms(boxes, scores, iou_threshold=0.5)- self.assert_close(actual, expected)-- def test_single_box(self, device, dtype):- boxes = torch.tensor([[0, 0, 10, 10]], device=device, dtype=dtype)- scores = torch.tensor([0.8], device=device, dtype=dtype)- expected = torch.tensor([0], device=device, dtype=torch.long)- actual = nms(boxes, scores, iou_threshold=0.5)- self.assert_close(actual, expected)-- def test_threshold_effect(self, device, dtype):- boxes = torch.tensor(- [- [0, 0, 10, 10],- [1, 1, 11, 11], # High overlap- ],- device=device,- dtype=dtype,- )- scores = torch.tensor([0.9, 0.8], device=device, dtype=dtype)- # Low threshold removes second box- out_low = nms(boxes, scores, iou_threshold=0.3)- self.assert_close(out_low, torch.tensor([0], device=device, dtype=torch.long))- # High threshold keeps both- out_high = nms(boxes, scores, iou_threshold=0.95)- self.assert_close(out_high, torch.tensor([0, 1], device=device, dtype=torch.long))-- def test_identical_scores(self, device, dtype):- boxes = torch.tensor(- [- [0, 0, 10, 10],- [5, 5, 15, 15],- ],- device=device,- dtype=dtype,- )- scores = torch.tensor([0.8, 0.8], device=device, dtype=dtype)- actual = nms(boxes, scores, iou_threshold=0.5)- # Ensure deterministic ordering (PyTorch NMS is stable)- expected = torch.tensor([0, 1], device=device, dtype=torch.long)- self.assert_close(actual, expected)-- def test_large_random(self, device, dtype):- torch.manual_seed(42)- boxes = torch.rand((1000, 4), device=device, dtype=dtype) * 100- boxes[:, 2:] += boxes[:, :2] # ensure x2 >= x1, y2 >= y1- scores = torch.rand((1000,), device=device, dtype=dtype)- out = nms(boxes, scores, iou_threshold=0.5)- assert out.ndim == 1- assert out.dtype == torch.long