YOLOv8模型预测
时间: 2023-12-26 20:28:54 浏览: 94
yolov8-models-cls.rar
YOLOv8是一种目标检测模型,可以用于检测图像或视频中的物体。下面是YOLOv8模型预测的示例代码:
```python
import cv2
import numpy as np
# 加载模型和权重
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')
# 获取输出层
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 加载类别标签
classes = []
with open('coco.names', 'r') as f:
classes = [line.strip() for line in f.readlines()]
# 加载图像
image = cv2.imread('image.jpg')
height, width, channels = image.shape
# 预处理图像
blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
# 运行前向传播
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)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
# 后处理结果
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
font = cv2.FONT_HERSHEY_SIMPLEX
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(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, label + ' ' + str(round(confidence, 2)), (x, y - 10), font, 0.5, color, 2)
# 显示结果图像
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这段代码使用OpenCV的dnn模块加载YOLOv8模型和权重,并进行预测。它首先加载模型和权重,然后加载类别标签。接下来,它加载图像并进行预处理。然后,它运行前向传播,得到输出结果。最后,它解析输出结果并进行后处理,将检测到的物体绘制在图像上并显示出来。
阅读全文