1. 背景
看了B站许多up主的视频,感觉YOLOV8各方面都很优秀,作为新手对它的期待很大,于是想实际跑跑看,边实践,边学习,记录过程。
本篇主要是博主在windows平台上部署YOLOV8的笔记,感兴趣的小伙伴请点赞、收藏、转发,也请大家持续关注后面的更新。
2. 部署过程
主要参考官方文档
2.1 快速安装
【A】打开命令行,输入面下的安装命令:
pip install ultralytics
可以看到安装成功。
【B】环境检查:
%python
>>> import ultralytics
>>> ultralytics.checks()
【C】运行demo code
参考官方文档中的python 代码示例,新建demo.py文件:
from ultralytics import YOLO
# 加载模型
model = YOLO("yolov8n.yaml") # 从头开始构建新模型
model = YOLO("yolov8n.pt") # 加载预训练模型(建议用于训练)
# 使用模型
model.train(data="coco128.yaml", epochs=3) # 训练模型
metrics = model.val() # 在验证集上评估模型性能
results = model("https://ultralytics.com/images/bus.jpg") # 对图像进行预测
success = model.export(format="onnx") # 将模型导出为 ONNX 格式
尝试运行:
python demo.py
博主的第一次运行,报错如下:
根据提示,在demo.py中添加KMP_DUPLICATE_LIB_OK开关:
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
from ultralytics import YOLO
# 加载模型
model = YOLO("yolov8n.yaml") # 从头开始构建新模型
model = YOLO("yolov8n.pt") # 加载预训练模型(建议用于训练)
# 使用模型
model.train(data="coco128.yaml", epochs=3) # 训练模型
metrics = model.val() # 在验证集上评估模型性能
results = model("https://ultralytics.com/images/bus.jpg") # 对图像进行预测
success = model.export(format="onnx") # 将模型导出为 ONNX 格式
再次运行,可以看到,在当前目录下会新建模型文件yolov8n.pt和训练过程文件夹runs,并下载了输入测试文件bus.jpg:
过程中,对CPU的消耗非常大:
运行完成后,可以看到输出结果:
image 1/1 E:\leaning\DeepLearning\YOLOV8\src\bus.jpg: 640x480 4 persons, 1 bus, 1 stop sign, 131.1ms
实际预测的对象:
可以看到预测是正确的。
至此,YOLOV8 win10 部署OK。
3. 功能验证
3.1 Predict
3.1.1 图片输入图片输出
为了让预测结果更为直观,我们将预测结果画框输出。
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
from PIL import Image
from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.pt') # pretrained YOLOv8n model
source = 'bus.jpg'
results = model(source) # return a list of Results objects
# Show the results
for r in results:
im_array = r.plot() # plot a BGR numpy array of predictions
im = Image.fromarray(im_array[..., ::-1]) # RGB PIL image
im.show() # show image
im.save('results.jpg') # save image
3.1.2 视频输入视屏输出
可以下载一段视屏文件,输出有预测框的视屏。
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
import cv2
from ultralytics import YOLO
# Load the YOLOv8 model
model = YOLO('yolov8n.pt')
# Open the video file
video_path = "003.avi"
cap = cv2.VideoCapture(video_path)
# Loop through the video frames
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
if success:
# Run YOLOv8 inference on the frame
results = model(frame)
# Visualize the results on the frame
annotated_frame = results[0].plot()
# Display the annotated frame
cv2.imshow("YOLOv8 Inference", annotated_frame)
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord("q"):
break
else:
# Break the loop if the end of the video is reached
break
# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()
输出视频效果:
YOLOv8 行人预测