首先这里是我的代码:
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的流程是这样的
输入 - 提案框列表 B,对应的置信度 S 和重叠阈值 N
输出 - 过滤后的提案列表 D
算法/步骤
这里所指的阈值只不过是
nms_threshold
.在
cv2.dnn.NMSBoxes
功能,nms_threshold
是用于非极大值抑制的 IOU 阈值。所以如果你有一个很大的值,你会强制两个框有很高的重叠(通常不是这种情况),只有当它与另一个框的 IOU 大于 0.8 时,才会删除该框。由于通常没有这么多重叠,因此不会删除这些框。减少此值将更容易删除冗余检测
希望这是有道理的
您可以阅读有关非极大值抑制的更多信息 here
关于python-3.x - 为什么 NMSboxes 没有消除多个边界框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66701910/