Search code examples
pythonmachine-learningdeep-learningimage-segmentationyolov8

YOLOv8 segmentation get class names when predicting multiple classes


How do I get the class names of segmented instances when detecting multiple classes in YOLOv8? The detections do not have a .cls attribute like here YOLOv8 get predicted class name. Also the docs do not seem to mention anything e.g. here

When I use the show=true argument in the prediction function, the classes are distinguished in the resulting image, but I cannot get them programmatically. My code that gets me all detections I wanjt but does not let me know which one is which:

from ultralytics import YOLO
model = YOLO("path/to/best.pt")
result = model.predict(os.path.join(cut_dir, im_name), save_conf=True, show=True)
if result[0].masks is not None:
    for counter, detection in enumerate(result[0].masks.data):
         detected = np.asarray(detection.cpu())                

Solution

  • For the segmentation task, you can refer to the boxes.cls property of the result object to get the detected class index, the same as for the detection task. model.names[class_index] will return the class name:

    from ultralytics import YOLO
    model = YOLO("path/to/best.pt")
    result = model.predict(os.path.join(cut_dir, im_name), save_conf=True, show=True)
    if result[0].masks is not None:
        for counter, detection in enumerate(result[0].masks.data):
             cls_id = int(result[0].boxes[counter].cls.item())
             cls_name = model.names[cls_id]