yolov8 图片推理并画框
时间: 2023-10-22 08:29:41 浏览: 251
您可以使用以下代码来使用YOLOv3模型进行图片推理并绘制边界框:
```python
import cv2
import numpy as np
# 加载模型和类别标签
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
with open('coco.names', 'r') as f:
classes = [line.strip() for line in f.readlines()]
# 图片路径
image_path = 'image.jpg'
# 加载图片并获取其宽度和高度
image = cv2.imread(image_path)
height, width = image.shape[:2]
# 创建一个blob,将图像进行预处理
blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)
# 设置模型的输入
net.setInput(blob)
# 运行前向传播,获取输出层的结果
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
outs = net.forward(output_layers)
# 初始化检测结果列表
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.5:
# 将边界框的坐标进行还原
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
# 将检测结果添加到列表中
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
# 对检测结果进行非最大值抑制
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 绘制边界框和类别标签
for i in indices:
i = i[0]
x, y, w, h = boxes[i]
label = classes[class_ids[i]]
confidence = confidences[i]
color = (255, 0, 0) # 设置边界框颜色为蓝色
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2) # 绘制边界框
cv2.putText(image, f'{label}: {confidence:.2f}', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2) # 绘制类别标签和置信度
# 显示结果图像
cv2.imshow('YOLOv3 Object Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请确保将YOLOv3权重文件('yolov3.weights')和模型配置文件('yolov3.cfg')放在正确的路径下,并且将类别标签文件('coco.names')与脚本放在同一目录下。您需要提供要推理的图像路径,并可以根据需要调整置信度阈值和非最大值抑制的参数。
阅读全文