一、准备条件
1.下载yolov8
https://github.com/ultralytics/ultralytics
2.安装python
https://www.python.org/ftp/python/3.8.0/python-3.8.0-amd64.exe
3.安装依赖
进入ultralytics-main,执行:
pip install -r requirements.txt
pip install -U ultralytics
二、标注
1.安装pyqt5
pip install pyqt5 -i https://pypi.tuna.tsinghua.edu.cn/simple
2.安装labelme
pip install labelme -i https://pypi.tuna.tsinghua.edu.cn/simple
3.启动
labelimg 图片文件路径 标注的类别txt文件路径 标注结果txt文件路径
labelimg D:/Desktop/BicycleImgs/JPEGImages D:/Desktop/BicycleImgs/predefined_classes.txt D:/Desktop/BicycleImgs/Annotations
predefined_classes.txt内容:
E-bike
三、训练
1.到ultralytics所在的目录:
D:\workspace_all\pyCharm\ultralytics-main\ultralytics
2.放置位置如下:
3.ebike.yaml内容如下:
# Helmet
train: datasets/ebike/train
val: datasets/ebike/valid
test: datasets/ebike/test
# Classes
names:
0: E-bike
4.在命令行,执行如下命令,进行训练:
yolo task=detect mode=train model=./models/yolov8s.pt data=./ebike.yaml epochs=300 batch=16
5.训练结果
四、跟踪
1.代码结构
2.代码
from collections import defaultdict
import cv2
import numpy as np
from ultralytics import YOLO
# Load the YOLOv8 model
model = YOLO('best.pt')
# Open the video file
video_path = "D:/Desktop/999/video.mp4"
cap = cv2.VideoCapture(video_path)
# 获取视频的帧率和尺寸
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# 保存画框视频
output = cv2.VideoWriter('D:/Desktop/999/output.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))
# 用于展示
cv2.namedWindow("YOLOv8 Tracking", 0)
cv2.resizeWindow("YOLOv8 Tracking", 1200, 900) # 设置窗口的长和宽
# Store the track history
track_history = defaultdict(lambda: [])
# Loop through the video frames
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
if success:
# Run YOLOv8 tracking on the frame, persisting tracks between frames
results = model.track(frame, persist=True)
# Get the boxes and track IDs
boxes = results[0].boxes.xywh.cpu()
if results[0].boxes.id == None:
continue
track_ids = results[0].boxes.id.int().cpu().tolist()
# Visualize the results on the frame
annotated_frame = results[0].plot()
# Plot the tracks
'''
for box, track_id in zip(boxes, track_ids):
x, y, w, h = box
track = track_history[track_id]
track.append((float(x), float(y))) # x, y center point
if len(track) > 30: # retain 90 tracks for 90 frames
track.pop(0)
# Draw the tracking lines
points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
cv2.polylines(annotated_frame, [points], isClosed=False, color=(230, 230, 230), thickness=10)
'''
# Display the annotated frame
cv2.imshow("YOLOv8 Tracking", annotated_frame)
# 保存视频
output.write(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()
output.release()
3.效果