实现基于YOLOv8的车辆跟踪与车速计算应用涉及以下几个步骤。这里我们假设你已经熟悉Python编程,并且已经安装了所需的库,如YOLOv8、OpenCV等。如果没有,可以先安装这些库:
pip install ultralytics opencv-python numpy opencv-contrib-python
步骤1:安装和配置YOLOv8
首先,安装YOLOv8库并下载预训练模型:
pip install ultralytics
步骤2:加载模型和配置环境
编写Python脚本来加载YOLOv8模型并配置摄像头或视频输入:
import cv2
from ultralytics import YOLO
# 加载YOLOv8预训练模型
model = YOLO('yolov8s.pt')
# 打开摄像头或视频文件
cap = cv2.VideoCapture(0) # 使用摄像头
# cap = cv2.VideoCapture('video.mp4') # 使用视频文件
while True:
ret, frame = cap.read()
if not ret:
break
# 进行检测
results = model(frame)
# 处理检测结果
for result in results:
for box in result.boxes:
x1, y1, x2, y2 = box.xyxy.cpu().numpy().astype(int)
confidence = box.conf.cpu().numpy()
class_id = int(box.cls.cpu().numpy())
if class_id == 2: # 仅检测车辆(类别ID 2 代表车辆)
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, f'Vehicle: {
confidence:.2f}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 显示结果
cv2.imshow('Vehicle Detection', frame)
# 按q键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
步骤3:车辆跟踪
为了实现车辆跟踪,可以使用OpenCV的跟踪器,例如KCF、CSRT、MOSSE等。这里使用CSRT跟踪器进行演示:
import cv2
from ultralytics import YOLO
# 加载YOLOv8预训练模型
model = YOLO('yolov8s.pt')
# 打开摄像头或视频文件
cap = cv2.VideoCapture(0) # 使用摄像头
# cap = cv2.VideoCapture('video.mp4') # 使用视频文件
trackers = cv2.MultiTracker_create()
while True:
ret, frame = cap.read()
if not ret:
break
# 进行检测
results = model(frame)
# 初始化跟踪器
for result in results:
for box in result.boxes:
x1, y1, x2, y2 = box.xyxy.cpu().numpy().astype(int)
class_id = int(box.cls.cpu().numpy())
if class_id == 2: # 仅检测车辆
tracker = cv2.TrackerCSRT_create()
trackers.add(tracker, frame, (x1, y1, x2 - x1, y2 - y1))
# 更新跟踪器
success,</