pythonyolo

Extract classes from yolo model


let us suppose that there is given image : enter image description here

i want to extract classes from given image using yolo model, so that those classes i can use for some monitoring purpose, i have run following code :

from ultralytics import YOLO
import matplotlib.pyplot as plt

model = YOLO("yolo11n.pt")
results =model("cat_dog.jpg")
for detection in results[0]:
    print(detection.probs)

and returned result is :

image 1/1 C:\Users\User\PycharmProjects\Artificial_Inteligence\cat_dog.jpg: 640x576 2 cats, 1 dog, 88.4ms
Speed: 3.1ms preprocess, 88.4ms inference, 1.5ms postprocess per image at shape (1, 3, 640, 576)
None
None
None

2 cats and 1 dog is returned as part of full string, but how to extract is seperately? for if-else condition? thanks in advance


Solution

  • Supposing you are using an object detection task model (because the results returned from the model additionally return the quantity of objects), you need to refer to the boxes property instead of probs (which is the classification task model property).

    from ultralytics import YOLO
    
    model = YOLO("yolo11n.pt")
    names = model.names # get the list of class names for this model
    results = model("cat_dog.jpg")
    for detection in results[0]:
        cls_id = int(detection.boxes.cls.item()) # get the detected object class ID
        cls_name = names[cls_id] # get the detected object class name
        print(cls_name)
    

    For more information, refer to the documentation of working with the results: https://docs.ultralytics.com/modes/predict/#working-with-results.

    To check what task your model implements, call:

    model.task