YOLOV8进行疲劳驾驶检测(一)训练模型和生成权重文件
本项目基于华为疲劳驾驶检测挑战赛展开,大家想要了解更多可以访问华为云官网[^1]。
1. 下载配置yolov8
下载网址: ultralytics-github仓库.
帮助文档网址: ultralytics-docs.
git clone https://github.com/ultralytics/ultralytics
配置使用环境
2. 数据准备 (datasets)
以coco128数据格式为例
coco128.yaml文件中设置了数据的输入位置
标签中的类别
- coco128
- images
- train2017
- 图片
- train2017
- labels
- train2017
- 标签(txt格式)
- train2017
- images
coco128下载网址:coco128.zip.
自训练数据集说明
- 需要配置一个自训练数据的yaml文件
- 使数据格式类似与coco128(注意标签需要是txt格式的)
3. 训练权重文件 (train)
首先需要注册一个wandb的账号,用于检测训练情况
在开始训练时需要输入wandb的key
wandb注册网址:wandb.ai
yolov8n.py下载:yolov8n.pt
from ultralytics import YOLO
import wandb
import asyncio
from multiprocessing import freeze_support
freeze_support
wandb.init(project='new_db')
# 建议提前下载yolov8n.pt,国内下载会很慢
model = YOLO('yolov8n.yaml')
model = YOLO('yolov8n.pt')
model = YOLO('yolov8n.yaml').load('yolov8n.pt')
model.train(data='new_data.yaml',epochs=300,imgsz=640)
训练好之后模型权重文件best.pt和last.pt自动保存在runs/train/路径下
可以将模型导出为onnx文件格式
from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.pt') # 加载官方模型
model = YOLO('path/to/best.pt') # 加载我们已经训练好的模型
# Export the model
model.export(format='onnx')
4. 模型预测 (predict)
通过Ultralytics模块内置方法可以对图片或者视频进行预测
# 对图片进行预测
import cv2
from ultralytics import YOLO
from matplotlib import pyplot as plt
model = YOLO('./runs/train16/weights/best.pt')
res = model(img1)
res_plotted = res[0].plot()
img1 = '../datasets/new_data/images/day_man_002_30_2_284.png'
image = cv2.imread(img1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.imshow(cv2.cvtColor(res_plotted, cv2.COLOR_BGR2RGB))
plt.show()
# 对视频进行预测
import cv2
from ultralytics import YOLO
# Load the YOLOv8 model
model = YOLO('./runs/train16/weights/best.pt')
# Open the video file
video_path = 'path/to/test.mp4'
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
# plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
# plt.imshow(cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB))
# plt.show()
# cv2.imshow('frame', frame)
cv2.imshow('labels', 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()
到这里已经能很好的检测出人脸和手机,接下来将对面部进行观测点识别,检测闭眼、打哈欠、转头等行为。