yolov8SOFTNMS
时间: 2025-01-22 10:08:03 浏览: 81
### YOLOv8中的Soft-NMS实现与应用
在目标检测领域,非极大值抑制(Non-Maximum Suppression, NMS)是一种用于消除冗余边界框的技术。传统的NMS方法通过设定阈值来过滤重叠度较高的候选框。然而,在某些情况下,这种方法可能会丢失一些有价值的预测结果。
为了改善这一情况,Soft-NMS被引入到YOLOv8中作为更灵活的选择之一[^3]。相比于标准的硬裁剪方式,Soft-NMS采用了一种渐进式的权重衰减机制,使得那些接近最高得分但未达到绝对最大值的提案也能保留下来并赋予较低置信度分数。
具体来说,当处理一组具有相似位置的目标时:
- 对于每一个检测框 \(i\) ,计算其与其他所有更高评分框之间的交并比(Intersection over Union, IoU)
- 如果某个高分框\(j\) 和当前框 \(i\) 的IoU超过了预设阈值,则不是简单地丢弃该低分框而是降低它的置信度:
\[ \text{score}_i = \text{score}_i * e^{-\frac{\text{IoU}_{ij}^2}{\sigma}} \]
其中参数 \(\sigma\) 控制着惩罚力度大小;随着两个矩形区域之间重合程度增加,原始得分会指数级减少。
以下是Python代码片段展示了如何在PyTorch框架下实现上述逻辑:
```python
import torch
def soft_nms(boxes, scores, iou_threshold=0.5, sigma=0.5):
"""
Apply Soft Non Maximum Suppression on the bounding boxes.
Args:
boxes (Tensor[N, 4]): Bounding boxes with format [x1,y1,x2,y2].
scores (Tensor[N]): Scores associated with each box.
iou_threshold (float): Threshold above which overlapping is considered significant.
sigma (float): Parameter controlling weight decay rate.
Returns:
Tensor[M]: Indices of selected boxes after applying Soft-NMS.
"""
# Sort by score descendingly
indices = torch.argsort(scores, dim=-1, descending=True)
keep = []
while len(indices) > 0:
current_idx = indices[0]
keep.append(current_idx.item())
if len(indices) == 1:
break
rest_indices = indices[1:]
overlaps = torchvision.ops.box_iou(
boxes[current_idx].unsqueeze(dim=0),
boxes[rest_indices])
weights = torch.exp(-overlaps ** 2 / sigma)
scores[rest_indices] *= weights.squeeze()
mask = scores >= threshold
indices = indices[mask][1:]
return torch.tensor(keep)
# Example Usage
from torchvision import ops as tvops
detections = ... # Your detections tensor here
scores = detections[:, 4]
bboxes = detections[:, :4]
selected_indices = soft_nms(bboxes, scores)
final_detections = detections[selected_indices]
```
此版本实现了基于指数加权的方法来进行软化操作,并且可以很容易地集成到现有的YOLOv8管道当中去以提高最终输出的质量和多样性。
阅读全文
相关推荐


















