yolov8内置跟踪器输出跟踪结果

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()
  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值