本文主要是介绍【保姆级教程】YOLOv8_Track多目标跟踪,快速运行,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、YOLOV8环境准备
1.1 下载安装最新的YOLOv8代码
仓库地址: https://github.com/ultralytics/ultralytics
1.2 配置环境
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
二、下载测试视频,预训练权重
测试视频
链接:https://pan.baidu.com/s/1xqu4aRxoOGlVLILKLSReqg
提取码:7g9r
–来自百度网盘超级会员V5的分享
预训练权重
在YOLOv8 github上下载预训练权重:yolov8n.pt
,ultralytics\ultralytics\路径下,新建weights
文件夹,预训练权重放入其中。
三、v8追踪
from collections import defaultdict
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import cv2
import numpy as npfrom ultralytics import YOLO# Load the YOLOv8 model
model = YOLO('weights/yolov8n.pt')# Open the video file
video_path = "video/car.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))
size = (width, height)# Store the track history
track_history = defaultdict(lambda: [])# Loop through the video frames
while cap.isOpened():# Read a frame from the videosuccess, frame = cap.read()if success:# Run YOLOv8 tracking on the frame, persisting tracks between framesresults = model.track(frame, persist=True)# Get the boxes and track IDsif results[0].boxes.id != None:boxes = results[0].boxes.xywh.cpu()track_ids = results[0].boxes.id.int().cpu().tolist()# Visualize the results on the frameannotated_frame = results[0].plot()# Plot the tracksfor box, track_id in zip(boxes, track_ids):x, y, w, h = boxtrack = track_history[track_id]track.append((float(x), float(y))) # x, y center pointif len(track) > 30: # retain 90 tracks for 90 framestrack.pop(0)# Draw the tracking linespoints = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))cv2.polylines(annotated_frame, [points], isClosed=False, color=(0, 0, 255), thickness=2)# Display the annotated framecv2.imshow("YOLOv8 Tracking", annotated_frame)# videoWriter.write(annotated_frame)# Break the loop if 'q' is pressedif cv2.waitKey(1) & 0xFF == ord("q"):breakelse:# Break the loop if the end of the video is reachedbreak# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()
v8 跟踪
这篇关于【保姆级教程】YOLOv8_Track多目标跟踪,快速运行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!