yolov8预测代码
时间: 2023-09-06 21:12:10 浏览: 250
以下是一个基本的 YOLOv8 预测代码示例:
```python
import cv2
import numpy as np
# 加载模型和类别列表
model = cv2.dnn.readNet("yolov8.weights", "yolov8.cfg")
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# 设置输入图像尺寸和缩放因子
input_size = (416, 416)
scale = 1 / 255.0
# 读取输入图像
image = cv2.imread("image.jpg")
# 将图像调整为指定尺寸并进行预处理
blob = cv2.dnn.blobFromImage(image, scale, input_size, (0, 0, 0), swapRB=True, crop=False)
# 设置网络的输入
model.setInput(blob)
# 运行网络并获取预测结果
output_layers_names = model.getUnconnectedOutLayersNames()
outputs = model.forward(output_layers_names)
# 解析预测结果
class_ids = []
confidences = []
boxes = []
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])
x = int(center_x - width / 2)
y = int(center_y - height / 2)
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, width, height])
# 应用非最大抑制
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 绘制边界框和标签
font_scale = 1
thickness = 1
for i in indices:
i = i[0]
box = boxes[i]
x, y, width, height = box
label = f"{classes[class_ids[i]]}: {confidences[i]:.2f}"
color = (255, 0, 0)
cv2.rectangle(image, (x, y), (x + width, y + height), color, thickness)
cv2.putText(image, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, font_scale, color, thickness)
# 显示结果图像
cv2.imshow("YOLOv8", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请确保在运行代码之前已经下载了 `yolov8.weights`、`yolov8.cfg` 和 `coco.names` 文件,并将其放置在正确的路径下。此外,你还需要安装 OpenCV 库来运行此代码。这段代码将加载预训练的 YOLOv8 模型,并在给定的图像上进行物体检测和标记。
阅读全文
相关推荐















