首先这是我的代码:
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)
算法
IOU 阈值是
nms_threshold
。
因此,如果你有一个更大的值,你实际上是在强制两个盒子有非常高的重叠(这将根据检测到的对象的类型而变化),并且只有当盒子的 IOU 大于0.8 与另一个盒子。由于通常没有那么多重叠,因此不会删除这些框。减小该值将更容易删除冗余检测
我希望这是有道理的。