dgenerate-ultralytics-headless 8.3.189__py3-none-any.whl → 8.3.191__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {dgenerate_ultralytics_headless-8.3.189.dist-info → dgenerate_ultralytics_headless-8.3.191.dist-info}/METADATA +1 -1
- {dgenerate_ultralytics_headless-8.3.189.dist-info → dgenerate_ultralytics_headless-8.3.191.dist-info}/RECORD +111 -109
- tests/test_cuda.py +6 -5
- tests/test_exports.py +1 -6
- tests/test_python.py +1 -4
- tests/test_solutions.py +1 -1
- ultralytics/__init__.py +1 -1
- ultralytics/cfg/__init__.py +16 -14
- ultralytics/cfg/datasets/VisDrone.yaml +4 -4
- ultralytics/data/annotator.py +6 -6
- ultralytics/data/augment.py +53 -51
- ultralytics/data/base.py +15 -13
- ultralytics/data/build.py +7 -4
- ultralytics/data/converter.py +9 -10
- ultralytics/data/dataset.py +24 -22
- ultralytics/data/loaders.py +13 -11
- ultralytics/data/split.py +4 -3
- ultralytics/data/split_dota.py +14 -12
- ultralytics/data/utils.py +31 -25
- ultralytics/engine/exporter.py +7 -4
- ultralytics/engine/model.py +16 -14
- ultralytics/engine/predictor.py +9 -7
- ultralytics/engine/results.py +59 -57
- ultralytics/engine/trainer.py +7 -0
- ultralytics/engine/tuner.py +4 -3
- ultralytics/engine/validator.py +3 -1
- ultralytics/hub/__init__.py +6 -2
- ultralytics/hub/auth.py +2 -2
- ultralytics/hub/google/__init__.py +9 -8
- ultralytics/hub/session.py +11 -11
- ultralytics/hub/utils.py +8 -9
- ultralytics/models/fastsam/model.py +8 -6
- ultralytics/models/nas/model.py +5 -3
- ultralytics/models/rtdetr/train.py +4 -3
- ultralytics/models/rtdetr/val.py +6 -4
- ultralytics/models/sam/amg.py +13 -10
- ultralytics/models/sam/model.py +3 -2
- ultralytics/models/sam/modules/blocks.py +21 -21
- ultralytics/models/sam/modules/decoders.py +11 -11
- ultralytics/models/sam/modules/encoders.py +25 -25
- ultralytics/models/sam/modules/memory_attention.py +9 -8
- ultralytics/models/sam/modules/sam.py +8 -10
- ultralytics/models/sam/modules/tiny_encoder.py +21 -20
- ultralytics/models/sam/modules/transformer.py +6 -5
- ultralytics/models/sam/modules/utils.py +7 -5
- ultralytics/models/sam/predict.py +32 -31
- ultralytics/models/utils/loss.py +29 -27
- ultralytics/models/utils/ops.py +10 -8
- ultralytics/models/yolo/classify/train.py +7 -5
- ultralytics/models/yolo/classify/val.py +10 -8
- ultralytics/models/yolo/detect/predict.py +3 -3
- ultralytics/models/yolo/detect/train.py +8 -6
- ultralytics/models/yolo/detect/val.py +23 -21
- ultralytics/models/yolo/model.py +14 -14
- ultralytics/models/yolo/obb/train.py +5 -3
- ultralytics/models/yolo/obb/val.py +13 -10
- ultralytics/models/yolo/pose/train.py +7 -5
- ultralytics/models/yolo/pose/val.py +11 -9
- ultralytics/models/yolo/segment/train.py +4 -5
- ultralytics/models/yolo/segment/val.py +12 -10
- ultralytics/models/yolo/world/train.py +9 -7
- ultralytics/models/yolo/yoloe/train.py +7 -6
- ultralytics/models/yolo/yoloe/val.py +10 -8
- ultralytics/nn/autobackend.py +40 -52
- ultralytics/nn/modules/__init__.py +3 -3
- ultralytics/nn/modules/block.py +12 -12
- ultralytics/nn/modules/conv.py +4 -3
- ultralytics/nn/modules/head.py +46 -38
- ultralytics/nn/modules/transformer.py +22 -21
- ultralytics/nn/tasks.py +2 -2
- ultralytics/nn/text_model.py +6 -5
- ultralytics/solutions/analytics.py +7 -5
- ultralytics/solutions/config.py +12 -10
- ultralytics/solutions/distance_calculation.py +3 -3
- ultralytics/solutions/heatmap.py +4 -2
- ultralytics/solutions/object_counter.py +5 -3
- ultralytics/solutions/parking_management.py +4 -2
- ultralytics/solutions/region_counter.py +7 -5
- ultralytics/solutions/similarity_search.py +5 -3
- ultralytics/solutions/solutions.py +38 -36
- ultralytics/solutions/streamlit_inference.py +8 -7
- ultralytics/trackers/bot_sort.py +11 -9
- ultralytics/trackers/byte_tracker.py +17 -15
- ultralytics/trackers/utils/gmc.py +4 -3
- ultralytics/utils/__init__.py +27 -77
- ultralytics/utils/autobatch.py +3 -2
- ultralytics/utils/autodevice.py +10 -10
- ultralytics/utils/benchmarks.py +11 -10
- ultralytics/utils/callbacks/comet.py +9 -9
- ultralytics/utils/callbacks/platform.py +2 -1
- ultralytics/utils/checks.py +20 -29
- ultralytics/utils/downloads.py +2 -2
- ultralytics/utils/export.py +12 -11
- ultralytics/utils/files.py +8 -7
- ultralytics/utils/git.py +139 -0
- ultralytics/utils/instance.py +8 -7
- ultralytics/utils/logger.py +7 -6
- ultralytics/utils/loss.py +15 -13
- ultralytics/utils/metrics.py +62 -62
- ultralytics/utils/nms.py +346 -0
- ultralytics/utils/ops.py +83 -251
- ultralytics/utils/patches.py +6 -4
- ultralytics/utils/plotting.py +18 -16
- ultralytics/utils/tal.py +1 -1
- ultralytics/utils/torch_utils.py +4 -2
- ultralytics/utils/tqdm.py +47 -33
- ultralytics/utils/triton.py +3 -2
- {dgenerate_ultralytics_headless-8.3.189.dist-info → dgenerate_ultralytics_headless-8.3.191.dist-info}/WHEEL +0 -0
- {dgenerate_ultralytics_headless-8.3.189.dist-info → dgenerate_ultralytics_headless-8.3.191.dist-info}/entry_points.txt +0 -0
- {dgenerate_ultralytics_headless-8.3.189.dist-info → dgenerate_ultralytics_headless-8.3.191.dist-info}/licenses/LICENSE +0 -0
- {dgenerate_ultralytics_headless-8.3.189.dist-info → dgenerate_ultralytics_headless-8.3.191.dist-info}/top_level.txt +0 -0
ultralytics/utils/nms.py
ADDED
@@ -0,0 +1,346 @@
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
2
|
+
|
3
|
+
import sys
|
4
|
+
import time
|
5
|
+
|
6
|
+
import torch
|
7
|
+
|
8
|
+
from ultralytics.utils import LOGGER
|
9
|
+
from ultralytics.utils.metrics import batch_probiou, box_iou
|
10
|
+
from ultralytics.utils.ops import xywh2xyxy
|
11
|
+
|
12
|
+
|
13
|
+
def non_max_suppression(
|
14
|
+
prediction,
|
15
|
+
conf_thres: float = 0.25,
|
16
|
+
iou_thres: float = 0.45,
|
17
|
+
classes=None,
|
18
|
+
agnostic: bool = False,
|
19
|
+
multi_label: bool = False,
|
20
|
+
labels=(),
|
21
|
+
max_det: int = 300,
|
22
|
+
nc: int = 0, # number of classes (optional)
|
23
|
+
max_time_img: float = 0.05,
|
24
|
+
max_nms: int = 30000,
|
25
|
+
max_wh: int = 7680,
|
26
|
+
rotated: bool = False,
|
27
|
+
end2end: bool = False,
|
28
|
+
return_idxs: bool = False,
|
29
|
+
):
|
30
|
+
"""
|
31
|
+
Perform non-maximum suppression (NMS) on prediction results.
|
32
|
+
|
33
|
+
Applies NMS to filter overlapping bounding boxes based on confidence and IoU thresholds. Supports multiple
|
34
|
+
detection formats including standard boxes, rotated boxes, and masks.
|
35
|
+
|
36
|
+
Args:
|
37
|
+
prediction (torch.Tensor): Predictions with shape (batch_size, num_classes + 4 + num_masks, num_boxes)
|
38
|
+
containing boxes, classes, and optional masks.
|
39
|
+
conf_thres (float): Confidence threshold for filtering detections. Valid values are between 0.0 and 1.0.
|
40
|
+
iou_thres (float): IoU threshold for NMS filtering. Valid values are between 0.0 and 1.0.
|
41
|
+
classes (List[int], optional): List of class indices to consider. If None, all classes are considered.
|
42
|
+
agnostic (bool): Whether to perform class-agnostic NMS.
|
43
|
+
multi_label (bool): Whether each box can have multiple labels.
|
44
|
+
labels (List[List[Union[int, float, torch.Tensor]]]): A priori labels for each image.
|
45
|
+
max_det (int): Maximum number of detections to keep per image.
|
46
|
+
nc (int): Number of classes. Indices after this are considered masks.
|
47
|
+
max_time_img (float): Maximum time in seconds for processing one image.
|
48
|
+
max_nms (int): Maximum number of boxes for NMS.
|
49
|
+
max_wh (int): Maximum box width and height in pixels.
|
50
|
+
rotated (bool): Whether to handle Oriented Bounding Boxes (OBB).
|
51
|
+
end2end (bool): Whether the model is end-to-end and doesn't require NMS.
|
52
|
+
return_idxs (bool): Whether to return the indices of kept detections.
|
53
|
+
|
54
|
+
Returns:
|
55
|
+
output (List[torch.Tensor]): List of detections per image with shape (num_boxes, 6 + num_masks)
|
56
|
+
containing (x1, y1, x2, y2, confidence, class, mask1, mask2, ...).
|
57
|
+
keepi (List[torch.Tensor]): Indices of kept detections if return_idxs=True.
|
58
|
+
"""
|
59
|
+
# Checks
|
60
|
+
assert 0 <= conf_thres <= 1, f"Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0"
|
61
|
+
assert 0 <= iou_thres <= 1, f"Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0"
|
62
|
+
if isinstance(prediction, (list, tuple)): # YOLOv8 model in validation model, output = (inference_out, loss_out)
|
63
|
+
prediction = prediction[0] # select only inference output
|
64
|
+
if classes is not None:
|
65
|
+
classes = torch.tensor(classes, device=prediction.device)
|
66
|
+
|
67
|
+
if prediction.shape[-1] == 6 or end2end: # end-to-end model (BNC, i.e. 1,300,6)
|
68
|
+
output = [pred[pred[:, 4] > conf_thres][:max_det] for pred in prediction]
|
69
|
+
if classes is not None:
|
70
|
+
output = [pred[(pred[:, 5:6] == classes).any(1)] for pred in output]
|
71
|
+
return output
|
72
|
+
|
73
|
+
bs = prediction.shape[0] # batch size (BCN, i.e. 1,84,6300)
|
74
|
+
nc = nc or (prediction.shape[1] - 4) # number of classes
|
75
|
+
extra = prediction.shape[1] - nc - 4 # number of extra info
|
76
|
+
mi = 4 + nc # mask start index
|
77
|
+
xc = prediction[:, 4:mi].amax(1) > conf_thres # candidates
|
78
|
+
xinds = torch.arange(prediction.shape[-1], device=prediction.device).expand(bs, -1)[..., None] # to track idxs
|
79
|
+
|
80
|
+
# Settings
|
81
|
+
# min_wh = 2 # (pixels) minimum box width and height
|
82
|
+
time_limit = 2.0 + max_time_img * bs # seconds to quit after
|
83
|
+
multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
|
84
|
+
|
85
|
+
prediction = prediction.transpose(-1, -2) # shape(1,84,6300) to shape(1,6300,84)
|
86
|
+
if not rotated:
|
87
|
+
prediction[..., :4] = xywh2xyxy(prediction[..., :4]) # xywh to xyxy
|
88
|
+
|
89
|
+
t = time.time()
|
90
|
+
output = [torch.zeros((0, 6 + extra), device=prediction.device)] * bs
|
91
|
+
keepi = [torch.zeros((0, 1), device=prediction.device)] * bs # to store the kept idxs
|
92
|
+
for xi, (x, xk) in enumerate(zip(prediction, xinds)): # image index, (preds, preds indices)
|
93
|
+
# Apply constraints
|
94
|
+
# x[((x[:, 2:4] < min_wh) | (x[:, 2:4] > max_wh)).any(1), 4] = 0 # width-height
|
95
|
+
filt = xc[xi] # confidence
|
96
|
+
x = x[filt]
|
97
|
+
if return_idxs:
|
98
|
+
xk = xk[filt]
|
99
|
+
|
100
|
+
# Cat apriori labels if autolabelling
|
101
|
+
if labels and len(labels[xi]) and not rotated:
|
102
|
+
lb = labels[xi]
|
103
|
+
v = torch.zeros((len(lb), nc + extra + 4), device=x.device)
|
104
|
+
v[:, :4] = xywh2xyxy(lb[:, 1:5]) # box
|
105
|
+
v[range(len(lb)), lb[:, 0].long() + 4] = 1.0 # cls
|
106
|
+
x = torch.cat((x, v), 0)
|
107
|
+
|
108
|
+
# If none remain process next image
|
109
|
+
if not x.shape[0]:
|
110
|
+
continue
|
111
|
+
|
112
|
+
# Detections matrix nx6 (xyxy, conf, cls)
|
113
|
+
box, cls, mask = x.split((4, nc, extra), 1)
|
114
|
+
|
115
|
+
if multi_label:
|
116
|
+
i, j = torch.where(cls > conf_thres)
|
117
|
+
x = torch.cat((box[i], x[i, 4 + j, None], j[:, None].float(), mask[i]), 1)
|
118
|
+
if return_idxs:
|
119
|
+
xk = xk[i]
|
120
|
+
else: # best class only
|
121
|
+
conf, j = cls.max(1, keepdim=True)
|
122
|
+
filt = conf.view(-1) > conf_thres
|
123
|
+
x = torch.cat((box, conf, j.float(), mask), 1)[filt]
|
124
|
+
if return_idxs:
|
125
|
+
xk = xk[filt]
|
126
|
+
|
127
|
+
# Filter by class
|
128
|
+
if classes is not None:
|
129
|
+
filt = (x[:, 5:6] == classes).any(1)
|
130
|
+
x = x[filt]
|
131
|
+
if return_idxs:
|
132
|
+
xk = xk[filt]
|
133
|
+
|
134
|
+
# Check shape
|
135
|
+
n = x.shape[0] # number of boxes
|
136
|
+
if not n: # no boxes
|
137
|
+
continue
|
138
|
+
if n > max_nms: # excess boxes
|
139
|
+
filt = x[:, 4].argsort(descending=True)[:max_nms] # sort by confidence and remove excess boxes
|
140
|
+
x = x[filt]
|
141
|
+
if return_idxs:
|
142
|
+
xk = xk[filt]
|
143
|
+
|
144
|
+
c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
|
145
|
+
scores = x[:, 4] # scores
|
146
|
+
if rotated:
|
147
|
+
boxes = torch.cat((x[:, :2] + c, x[:, 2:4], x[:, -1:]), dim=-1) # xywhr
|
148
|
+
i = TorchNMS.fast_nms(boxes, scores, iou_thres, iou_func=batch_probiou)
|
149
|
+
else:
|
150
|
+
boxes = x[:, :4] + c # boxes (offset by class)
|
151
|
+
# Speed strategy: torchvision for val or already loaded (faster), TorchNMS for predict (lower latency)
|
152
|
+
if "torchvision" in sys.modules:
|
153
|
+
import torchvision # scope as slow import
|
154
|
+
|
155
|
+
i = torchvision.ops.nms(boxes, scores, iou_thres)
|
156
|
+
else:
|
157
|
+
i = TorchNMS.nms(boxes, scores, iou_thres)
|
158
|
+
i = i[:max_det] # limit detections
|
159
|
+
|
160
|
+
output[xi] = x[i]
|
161
|
+
if return_idxs:
|
162
|
+
keepi[xi] = xk[i].view(-1)
|
163
|
+
if (time.time() - t) > time_limit:
|
164
|
+
LOGGER.warning(f"NMS time limit {time_limit:.3f}s exceeded")
|
165
|
+
break # time limit exceeded
|
166
|
+
|
167
|
+
return (output, keepi) if return_idxs else output
|
168
|
+
|
169
|
+
|
170
|
+
class TorchNMS:
|
171
|
+
"""
|
172
|
+
Ultralytics custom NMS implementation optimized for YOLO.
|
173
|
+
|
174
|
+
This class provides static methods for performing non-maximum suppression (NMS) operations on bounding boxes,
|
175
|
+
including both standard NMS and batched NMS for multi-class scenarios.
|
176
|
+
|
177
|
+
Methods:
|
178
|
+
nms: Optimized NMS with early termination that matches torchvision behavior exactly.
|
179
|
+
batched_nms: Batched NMS for class-aware suppression.
|
180
|
+
|
181
|
+
Examples:
|
182
|
+
Perform standard NMS on boxes and scores
|
183
|
+
>>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
|
184
|
+
>>> scores = torch.tensor([0.9, 0.8])
|
185
|
+
>>> keep = TorchNMS.nms(boxes, scores, 0.5)
|
186
|
+
"""
|
187
|
+
|
188
|
+
@staticmethod
|
189
|
+
def fast_nms(
|
190
|
+
boxes: torch.Tensor,
|
191
|
+
scores: torch.Tensor,
|
192
|
+
iou_threshold: float,
|
193
|
+
use_triu: bool = True,
|
194
|
+
iou_func=box_iou,
|
195
|
+
) -> torch.Tensor:
|
196
|
+
"""
|
197
|
+
Fast-NMS implementation from https://arxiv.org/pdf/1904.02689 using upper triangular matrix operations.
|
198
|
+
|
199
|
+
Args:
|
200
|
+
boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
|
201
|
+
scores (torch.Tensor): Confidence scores with shape (N,).
|
202
|
+
iou_threshold (float): IoU threshold for suppression.
|
203
|
+
use_triu (bool): Whether to use torch.triu operator for upper triangular matrix operations.
|
204
|
+
iou_func (callable): Function to compute IoU between boxes.
|
205
|
+
|
206
|
+
Returns:
|
207
|
+
(torch.Tensor): Indices of boxes to keep after NMS.
|
208
|
+
|
209
|
+
Examples:
|
210
|
+
Apply NMS to a set of boxes
|
211
|
+
>>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
|
212
|
+
>>> scores = torch.tensor([0.9, 0.8])
|
213
|
+
>>> keep = TorchNMS.nms(boxes, scores, 0.5)
|
214
|
+
"""
|
215
|
+
if boxes.numel() == 0:
|
216
|
+
return torch.empty((0,), dtype=torch.int64, device=boxes.device)
|
217
|
+
|
218
|
+
sorted_idx = torch.argsort(scores, descending=True)
|
219
|
+
boxes = boxes[sorted_idx]
|
220
|
+
ious = iou_func(boxes, boxes)
|
221
|
+
if use_triu:
|
222
|
+
ious = ious.triu_(diagonal=1)
|
223
|
+
# NOTE: handle the case when len(boxes) hence exportable by eliminating if-else condition
|
224
|
+
pick = torch.nonzero((ious >= iou_threshold).sum(0) <= 0).squeeze_(-1)
|
225
|
+
else:
|
226
|
+
n = boxes.shape[0]
|
227
|
+
row_idx = torch.arange(n, device=boxes.device).view(-1, 1).expand(-1, n)
|
228
|
+
col_idx = torch.arange(n, device=boxes.device).view(1, -1).expand(n, -1)
|
229
|
+
upper_mask = row_idx < col_idx
|
230
|
+
ious = ious * upper_mask
|
231
|
+
# Zeroing these scores ensures the additional indices would not affect the final results
|
232
|
+
scores[~((ious >= iou_threshold).sum(0) <= 0)] = 0
|
233
|
+
# NOTE: return indices with fixed length to avoid TFLite reshape error
|
234
|
+
pick = torch.topk(scores, scores.shape[0]).indices
|
235
|
+
return sorted_idx[pick]
|
236
|
+
|
237
|
+
@staticmethod
|
238
|
+
def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torch.Tensor:
|
239
|
+
"""
|
240
|
+
Optimized NMS with early termination that matches torchvision behavior exactly.
|
241
|
+
|
242
|
+
Args:
|
243
|
+
boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
|
244
|
+
scores (torch.Tensor): Confidence scores with shape (N,).
|
245
|
+
iou_threshold (float): IoU threshold for suppression.
|
246
|
+
|
247
|
+
Returns:
|
248
|
+
(torch.Tensor): Indices of boxes to keep after NMS.
|
249
|
+
|
250
|
+
Examples:
|
251
|
+
Apply NMS to a set of boxes
|
252
|
+
>>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
|
253
|
+
>>> scores = torch.tensor([0.9, 0.8])
|
254
|
+
>>> keep = TorchNMS.nms(boxes, scores, 0.5)
|
255
|
+
"""
|
256
|
+
if boxes.numel() == 0:
|
257
|
+
return torch.empty((0,), dtype=torch.int64, device=boxes.device)
|
258
|
+
|
259
|
+
# Pre-allocate and extract coordinates once
|
260
|
+
x1, y1, x2, y2 = boxes.unbind(1)
|
261
|
+
areas = (x2 - x1) * (y2 - y1)
|
262
|
+
|
263
|
+
# Sort by scores descending
|
264
|
+
_, order = scores.sort(0, descending=True)
|
265
|
+
|
266
|
+
# Pre-allocate keep list with maximum possible size
|
267
|
+
keep = torch.zeros(order.numel(), dtype=torch.int64, device=boxes.device)
|
268
|
+
keep_idx = 0
|
269
|
+
|
270
|
+
while order.numel() > 0:
|
271
|
+
i = order[0]
|
272
|
+
keep[keep_idx] = i
|
273
|
+
keep_idx += 1
|
274
|
+
|
275
|
+
if order.numel() == 1:
|
276
|
+
break
|
277
|
+
|
278
|
+
# Vectorized IoU calculation for remaining boxes
|
279
|
+
rest = order[1:]
|
280
|
+
xx1 = torch.maximum(x1[i], x1[rest])
|
281
|
+
yy1 = torch.maximum(y1[i], y1[rest])
|
282
|
+
xx2 = torch.minimum(x2[i], x2[rest])
|
283
|
+
yy2 = torch.minimum(y2[i], y2[rest])
|
284
|
+
|
285
|
+
# Fast intersection and IoU
|
286
|
+
w = (xx2 - xx1).clamp_(min=0)
|
287
|
+
h = (yy2 - yy1).clamp_(min=0)
|
288
|
+
inter = w * h
|
289
|
+
|
290
|
+
# Early termination: skip IoU calculation if no intersection
|
291
|
+
if inter.sum() == 0:
|
292
|
+
# No overlaps with current box, keep all remaining boxes
|
293
|
+
remaining_count = rest.numel()
|
294
|
+
keep[keep_idx : keep_idx + remaining_count] = rest
|
295
|
+
keep_idx += remaining_count
|
296
|
+
break
|
297
|
+
|
298
|
+
iou = inter / (areas[i] + areas[rest] - inter)
|
299
|
+
|
300
|
+
# Keep boxes with IoU <= threshold
|
301
|
+
mask = iou <= iou_threshold
|
302
|
+
order = rest[mask]
|
303
|
+
|
304
|
+
return keep[:keep_idx]
|
305
|
+
|
306
|
+
@staticmethod
|
307
|
+
def batched_nms(
|
308
|
+
boxes: torch.Tensor,
|
309
|
+
scores: torch.Tensor,
|
310
|
+
idxs: torch.Tensor,
|
311
|
+
iou_threshold: float,
|
312
|
+
use_fast_nms: bool = False,
|
313
|
+
) -> torch.Tensor:
|
314
|
+
"""
|
315
|
+
Batched NMS for class-aware suppression.
|
316
|
+
|
317
|
+
Args:
|
318
|
+
boxes (torch.Tensor): Bounding boxes with shape (N, 4) in xyxy format.
|
319
|
+
scores (torch.Tensor): Confidence scores with shape (N,).
|
320
|
+
idxs (torch.Tensor): Class indices with shape (N,).
|
321
|
+
iou_threshold (float): IoU threshold for suppression.
|
322
|
+
use_fast_nms (bool): Whether to use the Fast-NMS implementation.
|
323
|
+
|
324
|
+
Returns:
|
325
|
+
(torch.Tensor): Indices of boxes to keep after NMS.
|
326
|
+
|
327
|
+
Examples:
|
328
|
+
Apply batched NMS across multiple classes
|
329
|
+
>>> boxes = torch.tensor([[0, 0, 10, 10], [5, 5, 15, 15]])
|
330
|
+
>>> scores = torch.tensor([0.9, 0.8])
|
331
|
+
>>> idxs = torch.tensor([0, 1])
|
332
|
+
>>> keep = TorchNMS.batched_nms(boxes, scores, idxs, 0.5)
|
333
|
+
"""
|
334
|
+
if boxes.numel() == 0:
|
335
|
+
return torch.empty((0,), dtype=torch.int64, device=boxes.device)
|
336
|
+
|
337
|
+
# Strategy: offset boxes by class index to prevent cross-class suppression
|
338
|
+
max_coordinate = boxes.max()
|
339
|
+
offsets = idxs.to(boxes) * (max_coordinate + 1)
|
340
|
+
boxes_for_nms = boxes + offsets[:, None]
|
341
|
+
|
342
|
+
return (
|
343
|
+
TorchNMS.fast_nms(boxes_for_nms, scores, iou_threshold)
|
344
|
+
if use_fast_nms
|
345
|
+
else TorchNMS.nms(boxes_for_nms, scores, iou_threshold)
|
346
|
+
)
|