上周面试让我手写 nms , 写的马马虎虎吧… 计算 iou 差点儿没写出来…
先上一下 进行目标检测 bbox nms 的 OpenCV API
def NMSBoxes(bboxes, scores, score_threshold, nms_threshold, eta=None, top_k=None): # real signature unknown; restored from __doc__
"""
NMSBoxes(bboxes, scores, score_threshold, nms_threshold[, eta[, top_k]]) -> indices
. @brief Performs non maximum suppression given boxes and corresponding scores.
.
. * @param bboxes a set of bounding boxes to apply NMS.
. * @param scores a set of corresponding confidences.
. * @param score_threshold a threshold used to filter boxes by score.
. * @param nms_threshold a threshold used in non maximum suppression.
. * @param indices the kept indices of bboxes after NMS.
. * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$.
. * @param top_k if `>0`, keep at most @p top_k picked indices.
"""
[m, 4]
,bbox是left, top, width, height
(m,)
关于bboxes
参数为何是左上角坐标与wh,我是这么看的:
点开文档:
https://docs.opencv.org/4.6.0/d6/d0f/group__dnn.html
搜NMSBoxes
:
会发现有三个:
C++中根据bboxes
的类型,来判断到底用哪个,第三个是旋转目标检测的
这篇文章说:
https://blog.csdn.net/hjxu2016/article/details/103516407
cv::Rect
有很多别名,包括cv::Rect2d
在 cv::Rect
定义中:
https://docs.opencv.org/4.6.0/d2/d44/classcv_1_1Rect__.html
要传入左上角坐标和wh,其实具体还要看PythonAPI是怎么写的,但是基本这里就可以判断Python接口,NMSBoxes第一个参数需要传入 left, top, width, height
样的bbox
给个demo:
import numpy as np
import cv2
if __name__ == '__main__':
dets = np.array([[100,120,170,200,0.98],
[20,40,80,90,0.99],
[20,38,82,88,0.96],
[200,380,282,488,0.9],
[19,38,75,91, 0.8]])
nms_idx = cv2.dnn.NMSBoxes(dets[:, :-1], dets[:, -1], 0.5, 0.5, top_k=2)
print(dets[nms_idx])
print(nms_idx)
[[ 20. 40. 80. 90. 0.99]
[100. 120. 170. 200. 0.98]]
[1 0]
另外说一下,旋转目标检测有旋转过的bbox,也要计算iou, 进行NMS,在OpenCV中是这个API: cv2.dnn.NMSBoxesRotated
,来看下这个cv::RotatedRect
的定义:
https://docs.opencv.org/4.6.0/db/dd6/classcv_1_1RotatedRect.html#ae1be388780b8d5faf450be18cbbf30f1
参数需要中心,wh, 以及对应的角度
哦对了,这里也有softnms的实现,这是我没想到的:
https://docs.opencv.org/4.6.0/d6/d0f/group__dnn.html#gac568f9e7aac314c09ddbc73ab4dc4814
下一篇写Python实现:
https://blog.csdn.net/HaoZiHuang/article/details/126463032
有参考自:
https://blog.csdn.net/yapifeitu/article/details/105703625