yolov8推理代码
时间: 2023-09-09 15:13:28 浏览: 127
Yolov5 最简推理代码
4星 · 用户满意度95%
这里是YOLOv4的推理代码示例,YOLOv8与YOLOv4的实现类似,你可以根据YOLOv8的网络结构进行相应的调整。
```python
import cv2
import numpy as np
import time
# 加载模型
net = cv2.dnn.readNetFromDarknet('yolov4.cfg', 'yolov4.weights')
# 获取输出层
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 加载类别标签
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, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
# 前向传播
start_time = time.time()
outputs = net.forward(output_layers)
end_time = time.time()
# 解析输出结果
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] * 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])
# 非最大抑制
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 绘制边界框和标签
font = cv2.FONT_HERSHEY_PLAIN
colors = np.random.uniform(0, 255, size=(len(classes), 3))
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 = colors[class_ids[i]]
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
cv2.putText(image, f'{label} {confidence:.2f}', (x, y - 5), font, 1, color, 2)
# 显示结果
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 打印推理时间
print(f'Inference time: {end_time - start_time}s')
```
请确保你已下载YOLOv8的权重文件(`yolov8.weights`),YOLOv8的配置文件(`yolov8.cfg`)和类别标签文件(`coco.names`),并将它们放在相应的路径下。同时,将待检测的图像命名为`image.jpg`并放在同一目录下。
以上代码会读取图像并进行目标检测,将检测结果显示在图像上,并输出推理时间。你可以根据实际情况对代码进行调整和优化。
阅读全文