How to keep track of tracking ids while running over a video frame by frame?

I am running the following code that runs the model over a video frame by frame to detect objects, the issue is that in each frame. It doesn’t keep track of the previous ids, therefore, each frame gets processed like it’s a new frame which translates into objects getting assigned the same id say #1 in each unique frame. How can I keep track of previous ids so that it never assigns the same ID to different objects?


       
# open target video file
with VideoSink(TARGET_VIDEO_PATH, video_info) as sink:
    # loop over video frames
    for frame in generator:
        if frame_counter > video_info.total_frames:
            break
        frame_counter += 1
        
        results = model.track(frame)
        detections = sv.Detections.from_yolov8(results[0])
        if results[0].boxes.id is not None:
            detections.tracker_id = results[0].boxes.id.cpu().numpy().astype(int)
        
        labels = [
            f"#{tracker_id} {int(confidence*100)}%"
            for _, _, confidence, class_id, tracker_id
            in detections
        ]
        

        # annotate and display frame
        frame = box_annotator.annotate(scene=frame, detections=detections, labels=labels)
        # updating line counter
        line_counter.trigger(detections=detections)
        line_annotator.annotate(frame=frame, line_counter=line_counter)
        %matplotlib inline
        sv.plot_image(frame, (16, 16))

     
     

this code snippet results in

As soon as the bounding box disappears on the first object, the second object in frames gets ID #1.

Hi! We are moving the Ultralytics community to Discord. To receive support for your questions, problems, issues, etc. please join us on the new server: Ultralytics