Inizia

Segmentazione di istanze e tracking con Ultralytics YOLO26

Che cos'è la segmentazione di istanze?#

La segmentazione di istanze è un'attività di visione artificiale che consiste nell'identificare e delineare singoli oggetti in un'immagine a livello di pixel. A differenza della segmentazione semantica, che classifica i pixel solo in base alla categoria, la segmentazione di istanze assegna un'etichetta univoca e delimita con precisione ogni singola istanza di oggetto. È quindi fondamentale per applicazioni che richiedono una comprensione spaziale dettagliata, come l'imaging medico, la guida autonoma e l'automazione industriale.

Ultralytics YOLO26 delimita con precisione i contorni degli oggetti, mantenendo la velocità e l'efficienza per cui sono noti i modelli YOLO.

Nel pacchetto Ultralytics sono disponibili due tipi di tracking con segmentazione di istanze:

  • Segmentazione di istanze con oggetti di classe: a ogni oggetto di classe viene assegnato un colore univoco per distinguerlo visivamente con chiarezza.

  • Segmentazione di istanze con tracce degli oggetti: ogni traccia è rappresentata da un colore distinto, facilitando l'identificazione e il tracking tra i frame video.



Guarda: Segmentazione di istanze con tracking degli oggetti usando Ultralytics YOLO26

Campioni#

Segmentazione di istanzeSegmentazione di istanze + tracking degli oggetti
Segmentazione di istanze UltralyticsSegmentazione di istanze Ultralytics con tracking degli oggetti
Segmentazione di istanze UltralyticsSegmentazione di istanze Ultralytics con tracciamento degli oggetti

Segmenta e traccia con YOLO26#

La soluzione InstanceSegmentation esegue un modello di segmentazione YOLO26 su ogni fotogramma, disegna le maschere dei singoli oggetti e assegna un colore diverso a ogni istanza, così puoi tracciare i singoli oggetti nel video. Carica un modello -seg, ad esempio YOLO26n-seg, quindi eseguilo sulla sorgente tramite l'API Python o la CLI.

Segmentazione di istanze con Ultralytics YOLO
# Instance segmentation using Ultralytics YOLO26
yolo solutions isegment show=True

# Pass a source video
yolo solutions isegment source="path/to/video.mp4"

# Monitor the specific classes
yolo solutions isegment classes="[0, 5]"

Argomenti di InstanceSegmentation#

Ecco una tabella con gli argomenti di InstanceSegmentation:

ArgomentoTipoPredefinitoDescrizione
modelstrNonePercorso a un file modello Ultralytics YOLO.
line_widthint2Spessore delle linee dei riquadri, dei punti chiave e dei conteggi disegnati dalla soluzione.
verboseboolTrueAbilita il log per frame della soluzione, con forma dell'input, conteggi per classe e velocità di elaborazione. La chiamata di tracking è sempre silenziosa.

Puoi anche usare gli argomenti track all'interno della soluzione InstanceSegmentation:

ArgomentoTipoPredefinitoDescrizione
trackerstr'tracktrack.yaml'Specifica l'algoritmo di tracciamento da usare. Opzioni integrate: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml.
conffloat0.25Imposta la soglia di confidenza per le rilevazioni; valori più bassi consentono di tracciare più oggetti, ma possono includere falsi positivi.
ioufloat0.5Imposta la soglia di Intersezione sull'unione (IoU) per filtrare le rilevazioni sovrapposte.
classeslistNoneFiltra i risultati in base all'indice della classe. Ad esempio, classes=[0, 2, 3] traccia solo le classi specificate.
devicestrNoneSpecifica il dispositivo per l'inferenza (ad es. cpu, cuda:0 o 0). Consente di scegliere tra CPU, una GPU specifica o altri dispositivi di calcolo per l'esecuzione del modello.
imgszint or tuple640Dimensione dell'immagine di destinazione per l'inferenza: un intero per un'immagine quadrata o una coppia (height, width). Le forme vengono adattate allo stride del modello.
max_detint300Numero massimo di rilevazioni da mantenere per fotogramma prima del tracciamento, che limita gli oggetti elaborati da una soluzione nelle scene dense.
quantizeint or strNonePrecisione dell’inferenza: 16 (FP16) oppure 32/unset (FP32) per i modelli PyTorch e TorchScript quando non si usa la CPU; gli altri formati usano la precisione selezionata dal rispettivo artefatto e ambiente di esecuzione. Sostituisce l’argomento deprecato half.

Sono inoltre disponibili i seguenti argomenti di visualizzazione:

ArgomentoTipoPredefinitoDescrizione
showboolFalseSe True, mostra le immagini o i video annotati in una finestra. Utile per ottenere un riscontro visivo immediato durante lo sviluppo o i test.
show_confboolTrueMostra il punteggio di confidenza di ogni rilevamento accanto all'etichetta. Fornisce indicazioni sul grado di certezza del modello per ciascun rilevamento.
show_labelsboolTrueMostra le etichette di ogni rilevamento nell'output visivo. Permette di identificare immediatamente gli oggetti rilevati.
show_boxesboolTrueDisegna riquadri di delimitazione attorno agli oggetti rilevati. Essenziale per identificarli visivamente e localizzarli nelle immagini o nei frame video.

Applicazioni della segmentazione di istanze#

La segmentazione di istanze con YOLO26 ha numerose applicazioni pratiche in diversi settori:

Gestione e riciclo dei rifiuti#

YOLO26 può essere utilizzato negli impianti di gestione dei rifiuti per identificare e smistare diversi tipi di materiali. Il modello può segmentare con grande precisione rifiuti di plastica, cartone, metallo e altri materiali riciclabili, consentendo ai sistemi di smistamento automatizzati di trattare i rifiuti in modo più efficiente. Questo è particolarmente importante se si considera che viene riciclato solo circa il 10% dei 7 miliardi di tonnellate di rifiuti di plastica prodotti ogni anno nel mondo.

Veicoli autonomi#

Nelle auto a guida autonoma, la segmentazione di istanze aiuta a identificare e tracciare pedoni, veicoli, segnali stradali e altri elementi della strada a livello di pixel. Questa comprensione precisa dell'ambiente è fondamentale per la navigazione e le decisioni di sicurezza. Le prestazioni in tempo reale di YOLO26 lo rendono particolarmente adatto a queste applicazioni sensibili ai tempi.

Imaging medico#

La segmentazione di istanze può identificare e delineare tumori, organi o strutture cellulari nelle scansioni mediche. La capacità di YOLO26 di delimitare con precisione i contorni degli oggetti lo rende utile per la diagnostica medica e la pianificazione dei trattamenti.

Monitoraggio dei cantieri#

Nei cantieri, la segmentazione di istanze può tracciare macchinari pesanti, lavoratori e materiali. Aiuta a garantire la sicurezza monitorando la posizione delle attrezzature e rilevando quando i lavoratori entrano in aree pericolose, oltre a ottimizzare il flusso di lavoro e l'allocazione delle risorse.

Domande frequenti#

  • Per eseguire la segmentazione di istanze con Ultralytics YOLO26, inizializza la soluzione InstanceSegmentation con un modello di segmentazione YOLO26 ed elabora i fotogrammi video. Ecco un esempio di codice semplificato:

    import cv2
    
    from ultralytics import solutions
    
    cap = cv2.VideoCapture("path/to/video.mp4")
    assert cap.isOpened(), "Error reading video file"
    
    # Scrittore video
    w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
    video_writer = cv2.VideoWriter("instance-segmentation.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
    
    # Inizializza InstanceSegmentation
    isegment = solutions.InstanceSegmentation(
        show=True,  # visualizza l'output
        model="yolo26n-seg.pt",  # model="yolo26n-seg.pt" per la segmentazione degli oggetti con YOLO26.
    )
    
    # Elabora il video
    while cap.isOpened():
        success, im0 = cap.read()
        if not success:
            print("Video frame is empty or processing is complete.")
            break
        results = isegment(im0)
        video_writer.write(results.plot_im)
    
    cap.release()
    video_writer.release()
    cv2.destroyAllWindows()
  • La segmentazione di istanze identifica e delimita i singoli oggetti in un'immagine, assegnando a ciascun oggetto un'etichetta e una maschera univoche. Il tracciamento degli oggetti estende questa funzionalità assegnando ID coerenti agli oggetti nei fotogrammi video, così da seguire continuamente gli stessi oggetti nel tempo. Quando queste funzionalità vengono combinate, come nell'implementazione di YOLO26, puoi analizzare il movimento e il comportamento degli oggetti nei video mantenendo informazioni precise sui contorni.

  • Rispetto ai modelli a due stadi come Mask R-CNN o Faster R-CNN, Ultralytics YOLO26 offre prestazioni in tempo reale, precisione competitiva e facilità d'uso. YOLO26 elabora le immagini in un unico passaggio (rilevamento a uno stadio), risultando molto più veloce e mantenendo un'elevata precisione. Si integra inoltre con Ultralytics Platform per la gestione di modelli, dataset e pipeline di addestramento. YOLO26 offre un buon equilibrio per le applicazioni che richiedono sia velocità sia precisione.

  • Sì, Ultralytics offre diversi dataset adatti ad addestrare modelli YOLO26 per la segmentazione di istanze, tra cui COCO-Seg, COCO8-Seg (un sottoinsieme più piccolo per test rapidi), Package-Seg e Crack-Seg. Questi dataset includono le annotazioni a livello di pixel necessarie per le attività di segmentazione di istanze. Per applicazioni più specifiche, puoi anche creare dataset personalizzati seguendo il formato Ultralytics. Puoi trovare informazioni complete sui dataset e istruzioni per l'uso nella documentazione dei dataset Ultralytics.

Commenti99

Fai una domanda, condividi i tuoi risultati o aiuta qualcun altro.

  1. CatFatOwGitHub

    Hello, I am trying to analyze a video and see if features grow/shrink over time. I am currently trying to use instance segmentation with object tracking; however, specifying save_txt=True parameter in model.track saves every single prediction into a single huge txt file. Trying to count the frames by going through this large txt apparently doesn't work as the class ID are not in order and sorting it would lose all information.

    Is there any way for Ultralytics to save the txt files by frame number? For example, frame1.txt only contains the predictions of the first frame.

    Any help would be greatly appreciated!

    1
    1. Glenn JocherUltralytics

      For per-frame TXT saving with tracking, you'll need to process results in your video loop and write custom frame-specific files. Here's a minimal adaptation of the Instance Segmentation and Tracking example:

      frame_count = 0
      while cap.isOpened():
          ret, im0 = cap.read()
          if not ret: break
          
          results = model.track(im0, persist=True)
          
          # Save current frame's tracked objects
          with open(f'frame{frame_count}.txt', 'w') as f:
              for box, mask, track_id in zip(results[0].boxes, results[0].masks, results[0].boxes.id.int().cpu().tolist()):
                  f.write(f"{track_id} {box.cls.item()} {box.xywhn.tolist()} {mask.xy[0].tolist()}\n")
          
          frame_count += 1

      This creates individual frameX.txt files with tracking IDs, class IDs, normalized boxes, and mask coordinates. The official documentation shows similar frame processing in the Instance Segmentation with Object Tracking examples.

    2. Glenn JocherUltralytics

      For per-frame TXT saving during tracking, you'll need to process each frame individually in your video loop as shown in the Instance Segmentation with Object Tracking example. Here's a minimal adaptation that creates frame-specific files:

      frame_count = 0
      while cap.isOpened():
          ret, im0 = cap.read()
          if not ret: break
          
          results = model.track(im0, persist=True)
          
          with open(f'frame{frame_count}.txt', 'w') as f:
              for box, mask, track_id in zip(results[0].boxes, results[0].masks, results[0].boxes.id.int().cpu().tolist()):
                  f.write(f"{track_id} {box.cls.item()} {box.xywhn.tolist()} {mask.xy[0].tolist()}\n")
          
          frame_count += 1

      This creates individual frameX.txt files with tracking IDs, class IDs, normalized boxes, and mask coordinates per frame. The approach mirrors the frame processing shown in our official tracking documentation.

  2. pedmindsetGitHub

    Been trying to figure this out for a while now. I want to ask, can I use object counting in regions with instance sementation and tracking? You want to count vehicles that cross two specific regions, like so Object 001 crossed region A and region B. Is this possible to do

    1
    1. Glenn JocherUltralytics

      @pedmindset yes, it is possible to combine object counting in regions with instance segmentation and tracking using Ultralytics YOLO11. You can use the track method to assign consistent IDs to objects across frames and define regions to monitor their crossings. For guidance, refer to the segmentation and tracking examples in the Instance Segmentation and Tracking Guide. Let us know if you need further clarification!

  3. DP1701GitHub

    Cool, but I can't define an imgsz via solutions.InstanceSegmentation(…). Is there another option for this?

    1. Glenn JocherUltralytics

      solutions.InstanceSegmentation is a higher-level wrapper and doesn’t currently expose imgsz directly; if you need to control input size, run segmentation+tracking via the core YOLO(...).track() API (supports imgsz) as shown in the Tracking mode docs and keep using the Instance Segmentation and Tracking guide for solution-level usage.

      from ultralytics import YOLO
      
      model = YOLO("yolo26n-seg.pt")
      results = model.track(source="path/to/video.mp4", imgsz=640, show=True, tracker="botsort.yaml")
  4. CatFatOwGitHub

    Hello, I noticed that when using tracking mode compared to normal segmentation prediction, the number of features predicted decreased by quite a lot for feature dense videos even if I use the same parameters of confidence and maximum detection?

    1. Glenn JocherUltralytics

      @CatFatOw great observation! This is actually expected behavior when using tracking mode compared to plain segmentation. Tracking algorithms apply additional filtering beyond confidence thresholds to maintain stable tracks, which can reduce the total number of detections.

      Here are a few things that might help increase detections while maintaining tracking:

      # Try adjusting these tracking-specific parameters
      results = model.track(
          frame, 
          persist=True,
          conf=0.3,  # Lower confidence threshold
          iou=0.5,   # Adjust IoU threshold for NMS
          max_det=1000,  # Increase max detections
          tracker="bytetrack.yaml"  # Try different trackers
      )

      You can also experiment with different tracking algorithms - ByteTrack tends to be more permissive with new track creation compared to BoTSORT. The trade-off is between detection sensitivity and tracking stability, where tracking prioritizes consistent object IDs over detecting every possible instance.

      If you need maximum detection sensitivity, consider running both modes and using tracking results only when you need the temporal consistency.

  5. Mauricio566GitHub

    Hello. Please, I need your help. I know exactly what segmenting an object is and how to do it. But I don't know what to do with an already segmented object or pixel mask. You can find a lot of information online about "how to segment a model or fit it to your dataset," but they don't tell you what to do with those masks in real projects. Can you give me some ideas or help, please? for r in results:
    if r.masks is not None: mask = r.masks.data[0].cpu().numpy() there is the mask but honestly I don't know what to do. thanks

  6. e-roeGitHub

    Hello Glenn, thanks for the example! Actually, I had already figured it out—it was more of a suggestion for the documentation examples. []´s

    1. Glenn JocherUltralytics

      Thank you for the suggestion! We always welcome community contributions to improve our documentation through GitHub Pull Requests. Feel free to submit any specific improvements you'd like to see in the Instance Segmentation with Object Tracking guide.

      1
  7. e-roeGitHub

    Hello, Wouldn't it be good to have a complete example showing how to extract the track ID, contour points, class, and confidence? These methods that handle everything automatically end up being of little practical use, and finding this information in the documentation is quite challenging—it's often easier to find from third-party sources. []´s

    1. Glenn JocherUltralytics(modificato)

      @e-roe thanks for your feedback! You can access track IDs, classes, masks, and confidence scores directly from the results object. Here's a concise example showing how to extract these details:

      results = isegment(im0)
      for i in range(len(isegment.clss)):
          track_id = isegment.track_ids[i]
          class_name = isegment.names[isegment.clss[i]]
          confidence = isegment.confs[i]
          mask = isegment.masks[i].data[0].numpy()  # Binary mask array
          contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

      For full implementation details, see the InstanceSegmentation reference in our documentation. Let us know if you need further clarification!

  8. expen6veGitHub

    Hi! I tried training a pretrained yolov8m-seg model on our custom 1 class dataset consisting of 1,307 images with 5 augmentations like:

    Flip: Horizontal, Vertical Rotation: Between -15° and +15° Saturation: Between -25% and +25% Blur: Up to 1.4px Noise: Up to 1.49% of pixels

    with these training configurations:

    # Train the model
    results = model.train(
        data="data6.yaml",
        epochs=250,
        imgsz=320,
        batch=8,
        workers=4,
        device=device,
        patience=18,
        copy_paste=0.1  # Add this line to enable copy-paste augmentation
    )

    this is my 16th model training as i tried testing out from 200+ images that and so on. In my val plots, i always get bad results. What can i further do to make a good model? it stopped training at 128 with the results below:

    epoch,time,train/box_loss,train/seg_loss,train/cls_loss,train/dfl_loss,metrics/precision(B),metrics/recall(B),metrics/mAP50(B),metrics/mAP50-95(B),metrics/precision(M),metrics/recall(M),metrics/mAP50(M),metrics/mAP50-95(M),val/box_loss,val/seg_loss,val/cls_loss,val/dfl_loss,lr/pg0,lr/pg1,lr/pg2

    126,4123.96,0.47628,0.76702,0.30532,0.85667,0.9862,0.96565,0.98972,0.94445,0.9775,0.97566,0.98923,0.83189,0.35178,0.67432,0.26286,0.89191,0.00101,0.00101,0.00101 127,4156.45,0.47613,0.76458,0.30439,0.85872,0.96877,0.98339,0.98913,0.94227,0.98701,0.96962,0.99053,0.83626,0.34228,0.67744,0.25083,0.88958,0.00100208,0.00100208,0.00100208

    1. Glenn JocherUltralytics(modificato)

      @expen6ve thank you for sharing your training details. For improved segmentation results with YOLO26, consider these adjustments:

      1. Dataset Size: 1.3k images may be insufficient for robust segmentation. Aim for ≥5k high-quality annotated images.
      2. Augmentation Tuning: Reduce rotation range (try ±5°) and remove noise augmentation, which can degrade mask precision.
      3. Hyperparameters: Increase imgsz to 640 (standard for segmentation tasks) and lower learning rate to 0.0001 with cosine scheduler.
      4. Model Selection: Try YOLO26s-seg instead of medium-sized models for better generalization on limited data.

      For detailed guidance, see the Segmentation Training Tips in our documentation.

  9. ShreyasChhetriGitHub

    Hi can we implement a Reinforcement Learning function up above the Yolo training function for more accuracy can it happen ?

    1. Glenn JocherUltralytics

      @ShreyasChhetri integrating reinforcement learning (RL) with YOLO training is an interesting idea, but YOLO models are not inherently designed for RL workflows. While it is theoretically possible, it would require substantial custom development outside the scope of the provided Ultralytics framework. You might consider exploring hybrid approaches combining RL and computer vision if your use case demands it. For standard training, refer to the existing YOLO training documentation: https://docs.ultralytics.com/modes/train.

  10. ZhangAiyiGitHub

    I have a question when run the code for Instance Segmentation with Object Tracking. The pycharm said UnicodeEncodeError: 'gbk' codec can't encode character '\u274c' in position 401: illegal multibyte sequence. Does anyone have the similar question? Thank you.

    1. Glenn JocherUltralytics

      @ZhangAiyi it seems like you're encountering a Unicode encoding issue. You can try setting your environment's encoding to UTF-8 in PyCharm to resolve this. If the problem persists, please check the PyCharm settings or your system's locale configuration.