from collections import defaultdict
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
import cv2
import numpy as np
from ultralytics import YOLO
# Load the YOLOv8 model
model = YOLO('ultralytics/best_all.pt')
with open("test.txt", "r", encoding="utf-8") as file:#内容为训练集的序号
# 读取所有行
lines = file.readlines()
for video in lines:
path=video.strip()
video_path=os.path.join("H:/shipMOT/data/test/",path,path+".mp4")#视频路径
file_path=os.path.join("I:/ultralytics/runs/track",path+".txt")#输出的跟踪结果
# Open the video file
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)
count=0;
# Store the track history
track_history = defaultdict(lambda: [])
with open(file_path,'a') as file:
# 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,racker="ultralytics/cfg/trackers/botsort.yaml",show=False)#使用内置的跟踪器,比如可以修改成bytetrack.yaml
count+=1#帧数,默认开始是第一帧
# Get the boxes and track IDs
if results[0].boxes.id != None:
boxes1= results[0].boxes.data.cpu()
boxes2=results[0].boxes.xywh.cpu()
track_ids = results[0].boxes.id.int().cpu().tolist()
# Visualize the results on the frame
annotated_frame = results[0].plot()
# Plot the tracks
for box1, track_id,box2 in zip(boxes1, track_ids,boxes2):
x, y, w1, h1 ,i,j,k= box1
x1,y1,w,h=box2
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)
file.write(str(count)+','+str(track_id)+','+str(x.item())+','+str(y.item())+','+str(w.item())+','+str(h.item())+','+'-1'+','+'-1'+','+'-1'+'\n')
if cv2.waitKey(1) & 0xFF == ord("q"):
break
else:
break
file.close()
yolov8内置跟踪器输出跟踪结果
最新推荐文章于 2024-07-03 19:57:49 发布