NMS原理
以目标检测为例:
- 目标检测推理过程中会产生很多检测框(目标检测推理过程中会产生很多检测框(A,B,C,D,E,F等),其中很多检测框都是检测同一个目标,但最终每个目标只需要一个检测框。
- NMS选择那个得分最高的检测框(假设是C),再将C与剩余框计算相应的IOU值,当IOU值超过所设定的阈值(普遍设置为0.5),即对超过阈值的框进行抑制,抑制的做法是将检测框的得分设置为0,
- 如此一轮过后,在剩下检测框中继续寻找得分最高的,再抑制与之IOU超过阈值的框,直到最后会保留几乎没有重叠的框。
- 这样基本可以做到每个目标只剩下一个检测框。
NMS代码模板
形式是 x1 y1 x2 y2 conf label顺序 坐标是恢复成原图数值的(可以看下面的例子)
import numpy as np
def yolo_nms_multi_class(predictions, iou_threshold=0.45, conf_threshold=0.25):
"""
"""
predictions = np.array(predictions)
# 过滤掉置信度低于阈值的框 x1 y1 x2 y2 conf label顺序 坐标是恢复成原图数值的
keep_indices = predictions[:, 4].astype(float) > conf_threshold
predictions = predictions[keep_indices]
if len(predictions) == 0:
return []
# 获取唯一类别标签(字符串形式)
unique_classes = np.unique(predictions[:, 5])
nms_results = []
# 对每个类别分别进行 NMS
for cls in unique_classes:
cls_predictions = predictions[predictions[:, 5] == cls]
boxes = cls_predictions[:, :4].astype(float)
scores = cls_predictions[:, 4].astype(float)
x1 = boxes