获取目标检测结果边界框信息的具体代码
时间: 2023-09-16 11:12:16 浏览: 63
以下是获取目标检测结果边界框信息的Python代码示例:
```python
# 导入必要的包
import cv2
import numpy as np
# 加载图像和模型
image = cv2.imread('image.jpg')
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
# 获取输出层信息
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 执行前向传递并获取输出
blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
outputs = net.forward(output_layers)
# 解析输出并提取边界框信息
boxes = []
confidences = []
class_ids = []
for output in outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
center_x = int(detection[0] * image.shape[1])
center_y = int(detection[1] * image.shape[0])
width = int(detection[2] * image.shape[1])
height = int(detection[3] * image.shape[0])
left = int(center_x - width / 2)
top = int(center_y - height / 2)
boxes.append([left, top, width, height])
confidences.append(float(confidence))
class_ids.append(class_id)
# 应用非最大值抑制(NMS)以去除重叠的边界框
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 打印检测到的物体的边界框信息
for i in indices:
i = i[0]
box = boxes[i]
left = box[0]
top = box[1]
width = box[2]
height = box[3]
label = str(classes[class_ids[i]])
confidence = confidences[i]
print(f'{label}: ({left}, {top}) - ({left + width}, {top + height}), confidence: {confidence}')
```
该代码首先加载图像和模型,然后执行前向传递并获取输出。接下来,它解析输出并提取每个检测到的物体的边界框信息,包括左上角坐标、宽度和高度。最后,它应用非最大值抑制(NMS)以去除重叠的边界框,并打印每个检测到的物体的边界框信息和置信度。