为什么NMSboxes不消除多个边界框?
首先这里是我的代码:
image = cv2.imread(filePath)
height, width, channels = image.shape
# USing blob function of opencv to preprocess image
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416),
swapRB=True, crop=False)
#Detecting objects
net.setInput(blob)
outs = net.forward(output_layers)
# Showing informations on the screen
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.7:
# Object detected
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
# Rectangle coordinates
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
indexes = cv2.dnn.NMSBoxes(boxes, confidences,score_threshold=0.4,nms_threshold=0.8,top_k=1)
font = cv2.FONT_HERSHEY_PLAIN
colors = np.random.uniform(0, 255, size=(len(classes), 3))
labels = ['bicycle','car','motorbike','bus','truck']
for i in range(len(boxes)):
if i in indexes:
label = str(classes[class_ids[i]])
if label in labels:
x, y, w, h = boxes[i]
color = colors[class_ids[i]]
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
cv2.putText(image, label, (x, y + 30), font, 2, color, 3)
cv2.imshow(fileName,image)
我的问题是:是不是cv2.dnn.NMSBoxes应该消除多个边界框?那么为什么我仍然得到如下示例的输出:
我的预期是这样的:
我的代码做错了吗?有没有更好的选择?非常感谢您的帮助。
回答
NMS 的过程是这样的
Input - A list of Proposal boxes B,对应的置信度 S 和重叠阈值 N
输出 - 过滤后的建议列表 D
算法/步骤
- 选择confidence score最高的proposal,从B中移除,加入到最终的proposal list D中。(最初D为空)
- 现在将此提案与所有提案进行比较——计算该提案与其他提案的 IOU(交集)。如果 IOU 大于阈值 N,则从 B 中删除该提案
- 再次从 B 中剩余的提案中取出置信度最高的提案,将其从 B 中删除并添加到 D
- 再次用B中的所有proposals计算这个proposal的IOU,并剔除IOU高于阈值的框
- 重复这个过程,直到 B 中没有更多的提案为止
这里所指的阈值只不过是nms_threshold.
在cv2.dnn.NMSBoxes功能,nms_threshold是在非最大抑制所使用的阈值IOU。
所以如果你有一个很大的值,你会强制两个框有很高的重叠(通常不是这种情况),只有当它与另一个框的 IOU 大于 0.8 时,才会删除该框。由于通常没有这么多重叠,因此不会删除这些框。减少此值将更容易删除冗余检测
希望这是有道理的
您可以在此处阅读有关非极大值抑制的更多信息