How can i get the count of in and out?

203 views Asked by At

i'm writing a code to get the total object that move in and out and would like to save the count into a database later on. I currently i have this code but i'm not able to get the object count. Keep getting NONE

I have tried this

import cv2
import supervision as sv
from ultralytics import YOLO

def main():
    model = YOLO("models/yolov8l.pt")
    
    box_annotator = sv.BoxAnnotator(thickness=1, text_thickness=1, text_scale=0.5)
    line_annotator = sv.LineZoneAnnotator(thickness=1, text_thickness=1, text_scale=0.5)
    
    results = model.track(source="assets/vid2.mp4", stream=True)
    
    line_zone = sv.LineZone(start=sv.Point(600, 0), end=sv.Point(600, 300))
    
    for result in results:
        frame = result.orig_img

        detections = sv.Detections.from_yolov8(result)

        if result.boxes is not None and result.boxes.id is not None:
            detections.tracker_id = result.boxes.id.cpu().numpy().astype(int)

        detections = detections[detections.class_id != 0]

        labels = [
            f"#{detection[3]} {model.names[detection[2]]} {detection[1]: 0.2f}"
            for detection in detections
        ]

        frame = box_annotator.annotate(scene=frame, detections=detections, labels=labels)

        line_zone.trigger(detections=detections)
        line_counter = line_annotator.annotate(frame=frame, line_counter=line_zone)

        print(line_counter)

        cv2.imshow("yolov8", frame)

        if (cv2.waitKey(30) == 27):
            break

if __name__ == "__main__":
    main()

The print(line_counter) keep getting NONE but in the cv2.imshow i'm able to view the in & out number. But i want to get the in and out number

1

There are 1 answers

1
Geom On

Seems like you're trying to reinvent a bicycle a little. Why not use the persist argument of the .track() method?

results = model.track(source="assets/vid2.mp4", stream=True, persist=True)

It will track objects across frames and assign them IDs as soon as the given ID appears it enters the frame as soon as it disappears it's out of the frame.