Segmentación de instancias y seguimiento con Ultralytics YOLO26
¿Qué es la segmentación de instancias?#
La segmentación de instancias es una tarea de visión artificial que consiste en identificar y delimitar objetos individuales de una imagen a nivel de píxel. A diferencia de la segmentación semántica, que solo clasifica los píxeles por categoría, la segmentación de instancias asigna etiquetas únicas y delimita con precisión cada instancia de objeto, por lo que es fundamental para aplicaciones que requieren una comprensión espacial detallada, como el diagnóstico por imagen, la conducción autónoma y la automatización industrial.
Ultralytics YOLO26 delimita con precisión los contornos de los objetos y mantiene la velocidad y la eficiencia por las que se conocen los modelos YOLO.
El paquete Ultralytics ofrece dos tipos de seguimiento de segmentación de instancias:
-
Segmentación de instancias con objetos de clase: A cada objeto de clase se le asigna un color único para distinguirlo visualmente con claridad.
-
Segmentación de instancias con seguimiento de objetos: Cada seguimiento se representa con un color distinto, lo que facilita su identificación y seguimiento a través de los fotogramas del vídeo.
Ver: Segmentación de instancias con seguimiento de objetos mediante Ultralytics YOLO26
Muestras#
| Segmentación de instancias | Segmentación de instancias + seguimiento de objetos |
|---|---|
![]() | ![]() |
| Segmentación de instancias de Ultralytics | Segmentación de instancias con seguimiento de objetos de Ultralytics |
Segmenta y sigue con YOLO26#
La solución InstanceSegmentation ejecuta un modelo de segmentación YOLO26 en cada fotograma, dibuja máscaras para cada objeto y colorea cada instancia por separado para que puedas seguir objetos individuales a lo largo de un vídeo. Carga un modelo -seg, como YOLO26n-seg, y ejecútalo en tu fuente con la API de Python o la CLI.
# 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]"Argumentos de InstanceSegmentation#
Aquí tienes una tabla con los argumentos de InstanceSegmentation:
| Argumento | Tipo | Predeterminado | Descripción |
|---|---|---|---|
model | str | None | Ruta a un archivo de modelo Ultralytics YOLO. |
line_width | int | 2 | Grosor de línea de los cuadros, puntos clave y recuentos que dibuja la solución. |
verbose | bool | True | Activa el registro por fotograma de la forma de entrada, los recuentos por clase y la velocidad de procesamiento de la solución. La llamada de seguimiento en sí siempre es silenciosa. |
También puedes usar argumentos de track en la solución InstanceSegmentation:
| Argumento | Tipo | Predeterminado | Descripción |
|---|---|---|---|
tracker | str | 'tracktrack.yaml' | Especifica el algoritmo de seguimiento que se va a usar. Opciones integradas: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml. |
conf | float | 0.25 | Establece el umbral de confianza de las detecciones; los valores más bajos permiten seguir más objetos, pero pueden incluir falsos positivos. |
iou | float | 0.5 | Establece el umbral de intersección sobre unión (IoU) para filtrar las detecciones solapadas. |
classes | list | None | Filtra los resultados por índice de clase. Por ejemplo, classes=[0, 2, 3] solo sigue las clases especificadas. |
device | str | None | Especifica el dispositivo para la inferencia (p. ej., cpu, cuda:0 o 0). Permite elegir entre CPU, una GPU concreta u otros dispositivos de cálculo para ejecutar el modelo. |
imgsz | int or tuple | 640 | Tamaño de imagen de destino para la inferencia: un entero para una imagen cuadrada o una pareja (height, width). Las dimensiones se ajustan al stride del modelo. |
max_det | int | 300 | Número máximo de detecciones que se conservan por fotograma antes del seguimiento, lo que limita los objetos que procesa una solución en escenas densas. |
quantize | int or str | None | Precisión de inferencia: 16 (FP16) o 32/unset (FP32) para los modelos PyTorch y TorchScript fuera de CPU; los demás formatos usan la precisión que seleccionen el artefacto y el entorno de ejecución. Sustituye al argumento obsoleto half. |
Además, están disponibles los siguientes argumentos de visualización:
| Argumento | Tipo | Predeterminado | Descripción |
|---|---|---|---|
show | bool | False | Si True, muestra las imágenes o los vídeos anotados en una ventana. Es útil para obtener información visual inmediata durante el desarrollo o las pruebas. |
show_conf | bool | True | Muestra la puntuación de confianza de cada detección junto a su etiqueta. Permite conocer el grado de certeza del modelo para cada detección. |
show_labels | bool | True | Muestra etiquetas para cada detección en la salida visual. Facilita la identificación inmediata de los objetos detectados. |
show_boxes | bool | True | Dibuja cuadros delimitadores alrededor de los objetos detectados. Es esencial para identificar visualmente y localizar objetos en imágenes o fotogramas de vídeo. |
Aplicaciones de la segmentación de instancias#
La segmentación de instancias con YOLO26 tiene numerosas aplicaciones reales en diversos sectores:
Gestión y reciclaje de residuos#
YOLO26 se puede utilizar en instalaciones de gestión de residuos para identificar y clasificar distintos tipos de materiales. El modelo puede segmentar residuos de plástico, cartón, metal y otros materiales reciclables con gran precisión, lo que permite a los sistemas de clasificación automatizados procesar los residuos de forma más eficiente. Esto es especialmente valioso si se tiene en cuenta que solo se recicla alrededor del 10 % de los 7 000 millones de toneladas de residuos plásticos que se generan en todo el mundo.
Vehículos autónomos#
En los coches autónomos, la segmentación de instancias ayuda a identificar y seguir peatones, vehículos, señales de tráfico y otros elementos de la carretera a nivel de píxel. Esta comprensión precisa del entorno es fundamental para la navegación y las decisiones de seguridad. El rendimiento en tiempo real de YOLO26 lo hace idóneo para estas aplicaciones con plazos críticos.
Diagnóstico por imagen#
La segmentación de instancias puede identificar y delimitar tumores, órganos o estructuras celulares en exploraciones médicas. La capacidad de YOLO26 para delimitar con precisión los límites de los objetos resulta valiosa para el diagnóstico médico y la planificación de tratamientos.
Supervisión de obras#
En las obras, la segmentación de instancias puede seguir maquinaria pesada, trabajadores y materiales. Esto contribuye a garantizar la seguridad al supervisar la posición de los equipos y detectar cuándo los trabajadores entran en zonas peligrosas, además de optimizar el flujo de trabajo y la asignación de recursos.
Preguntas frecuentes#
Para realizar la segmentación de instancias con Ultralytics YOLO26, inicializa la solución
InstanceSegmentationcon un modelo de segmentación YOLO26 y procesa los fotogramas de vídeo con ella. Aquí tienes un ejemplo de código simplificado:import cv2 from ultralytics import solutions cap = cv2.VideoCapture("path/to/video.mp4") assert cap.isOpened(), "Error reading video file" # Escritor de vídeo 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)) # Inicializar InstanceSegmentation isegment = solutions.InstanceSegmentation( show=True, # mostrar el resultado model="yolo26n-seg.pt", # model="yolo26n-seg.pt" para segmentar objetos con YOLO26. ) # Procesar el vídeo 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 segmentación de instancias identifica y delimita objetos individuales en una imagen, y asigna a cada objeto una etiqueta y una máscara únicas. El seguimiento de objetos amplía esta función asignando identificadores coherentes a los objetos a lo largo de los fotogramas de vídeo, lo que permite seguir continuamente los mismos objetos con el paso del tiempo. Al combinar ambas funciones, como en la implementación de YOLO26, puedes analizar el movimiento y el comportamiento de los objetos en vídeos sin perder información precisa sobre sus contornos.
Ultralytics YOLO26 ofrece rendimiento en tiempo real, precisión competitiva y facilidad de uso frente a modelos de dos etapas como Mask R-CNN o Faster R-CNN. YOLO26 procesa imágenes en una sola pasada (detección de una etapa), por lo que es mucho más rápido y mantiene una alta precisión. También se integra con Ultralytics Platform para gestionar modelos, conjuntos de datos y canalizaciones de entrenamiento. YOLO26 ofrece un equilibrio excelente para aplicaciones que necesitan velocidad y precisión.
Sí, Ultralytics ofrece varios conjuntos de datos adecuados para entrenar modelos YOLO26 de segmentación de instancias, como COCO-Seg, COCO8-Seg (un subconjunto más pequeño para realizar pruebas rápidas), Package-Seg y Crack-Seg. Estos conjuntos de datos incluyen las anotaciones a nivel de píxel necesarias para las tareas de segmentación de instancias. Para aplicaciones más especializadas, también puedes crear conjuntos de datos personalizados siguiendo el formato de Ultralytics. Encontrarás toda la información sobre los conjuntos de datos y las instrucciones de uso en la documentación de conjuntos de datos de Ultralytics.
Comentarios99
Haz una pregunta, comparte tus resultados o ayuda a otra persona.
CatFatOw
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=Trueparameter inmodel.tracksaves 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
Glenn JocherUltralyticsFor 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 += 1This 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.
CatFatOw
Thank you!
Glenn JocherUltralyticsFor 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 += 1This 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.
pedmindset
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
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
trackmethod 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!
DP1701
Cool, but I can't define an imgsz via solutions.InstanceSegmentation(…). Is there another option for this?
Glenn JocherUltralyticssolutions.InstanceSegmentationis a higher-level wrapper and doesn’t currently exposeimgszdirectly; if you need to control input size, run segmentation+tracking via the coreYOLO(...).track()API (supportsimgsz) 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")
CatFatOw
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?
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.
CatFatOw
Ok, thank you for the reply!
Mauricio566
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. thankse-roe
Hello Glenn, thanks for the example! Actually, I had already figured it out—it was more of a suggestion for the documentation examples. []´s
Glenn JocherUltralyticsThank 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
e-roe
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
Glenn JocherUltralytics(editado)@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!
expen6ve
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
Glenn JocherUltralytics(editado)@expen6ve thank you for sharing your training details. For improved segmentation results with YOLO26, consider these adjustments:
- Dataset Size: 1.3k images may be insufficient for robust segmentation. Aim for ≥5k high-quality annotated images.
- Augmentation Tuning: Reduce rotation range (try ±5°) and remove noise augmentation, which can degrade mask precision.
- Hyperparameters: Increase imgsz to 640 (standard for segmentation tasks) and lower learning rate to 0.0001 with cosine scheduler.
- 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.
ShreyasChhetri
Hi can we implement a Reinforcement Learning function up above the Yolo training function for more accuracy can it happen ?
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.
ZhangAiyi
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.
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.

