Search code examples
pythonyoloyolov8

Taking many attributs from Yolo result


I want to take some attributs from Yolo result, this is the code.

from ultralytics import YOLO
from datetime import datetime

model = YOLO("yolov8n.pt")
source = "https://youtu.be/LNwODJXcvt4"
results = model(source, stream=True)

for result in results:
    if result[0] is not None:
        with open("result.txt", "a") as myfile:
            for idx, coordinate in enumerate(result[0].boxes.xywhn):
                dt_now = datetime.now()
                date = f"{dt_now.year}-{dt_now.month}-{dt_now.day}"
                time = f"{dt_now.hour}:{dt_now.minute}:{dt_now.second}:{dt_now.microsecond}"
                cls = int(result[0].boxes.cls[idx].item())
                path = result[0].path
                class_name = model.names[cls]
                conf = int(result[0].boxes.conf[0]*100)
                
                myfile.write(f"Name: {class_name} ({cls}),\nConfidence: {conf},\nCoordinate: [{coordinate[0].item()} {coordinate[1].item()} {coordinate[2].item()} {coordinate[3].item()}],\nDate: {date},\nTime: {time}\n\n")

i just want to ask is this good or there is some useless code? this to complecated for me to read


Solution

  • I added some comments for each nested block to help you understand what each one is for:

    from ultralytics import YOLO
    from datetime import datetime
    
    model = YOLO("yolov8n.pt")
    source = "https://youtu.be/LNwODJXcvt4"
    results = model(source, stream=True) # should be a list of the results obtained for each frame in the video
    
    for result in results: # for each frame
        if result[0] is not None: # if the model detected some objects
            with open("result.txt", "a") as myfile: # with this file opened
                for idx, coordinate in enumerate(result[0].boxes.xywhn): # for each detected object (actually for its index et its box coordinates) on the frame
                    dt_now = datetime.now() # get the current time
                    # format the date and time to be written on the file 
                    date = f"{dt_now.year}-{dt_now.month}-{dt_now.day}"
                    time = f"{dt_now.hour}:{dt_now.minute}:{dt_now.second}:{dt_now.microsecond}"
                    cls = int(result[0].boxes.cls[idx].item()) # the class of the detected object (as an integer value)
                    path = result[0].path # not quite sure what this is
                    class_name = model.names[cls] # the name of class of the detected object
                    conf = int(result[0].boxes.conf[0]*100) # the confidence score
                    
                    # writing all the above to a file
                    myfile.write(f"Name: {class_name} ({cls}),\nConfidence: {conf},\nCoordinate: [{coordinate[0].item()} {coordinate[1].item()} {coordinate[2].item()} {coordinate[3].item()}],\nDate: {date},\nTime: {time}\n\n")