Empezar

Modelo rápido Segment Anything (FastSAM)

El Fast Segment Anything Model (FastSAM) es una solución en tiempo real basada en CNN para la tarea Segment Anything. Esta tarea está diseñada para segmentar cualquier objeto de una imagen a partir de distintas indicaciones de interacción del usuario. FastSAM reduce considerablemente las necesidades computacionales y mantiene un rendimiento competitivo, por lo que es una opción práctica para diversas tareas de visión.



Ver: Seguimiento de objetos con FastSAM mediante Ultralytics

Arquitectura del modelo#

Descripción general de la arquitectura del modelo rápido Segment Anything (FastSAM)

Descripción general#

FastSAM está diseñado para superar las limitaciones del Segment Anything Model (SAM), un modelo Transformer pesado que requiere muchos recursos computacionales. FastSAM divide la tarea Segment Anything en dos etapas secuenciales: segmentación de todas las instancias y selección guiada por indicaciones. En la primera etapa, YOLOv8-seg genera las máscaras de segmentación de todas las instancias de la imagen. En la segunda, devuelve la región de interés correspondiente a la indicación.

Características principales#

  1. Solución en tiempo real: Gracias a la eficiencia computacional de las CNN, FastSAM ofrece una solución en tiempo real para la tarea Segment Anything, lo que la hace valiosa en aplicaciones industriales que requieren resultados rápidos.

  2. Eficiencia y rendimiento: FastSAM reduce considerablemente las necesidades computacionales y de recursos, a la vez que alcanza un rendimiento comparable al de SAM, lo que permite su uso en aplicaciones en tiempo real.

  3. Segmentación guiada por indicaciones: FastSAM puede segmentar cualquier objeto de una imagen siguiendo distintas indicaciones de interacción del usuario, lo que le proporciona flexibilidad y adaptabilidad en diversos escenarios.

  4. Basado en YOLOv8-seg: FastSAM se basa en YOLOv8-seg, un detector de objetos con una rama de segmentación de instancias. Esto le permite generar eficazmente las máscaras de segmentación de todas las instancias de una imagen.

  5. Resultados competitivos en benchmarks: En la tarea de propuesta de objetos de MS COCO, FastSAM obtiene puntuaciones altas a una velocidad considerablemente mayor que SAM en una única NVIDIA RTX 3090, lo que demuestra su eficiencia y capacidad.

  6. Aplicaciones prácticas: Este enfoque ofrece una solución práctica para muchas tareas de visión y funciona entre decenas y cientos de veces más rápido que los métodos Segment Anything anteriores.

  7. Viabilidad de la compresión de modelos: FastSAM demuestra que es posible reducir significativamente el esfuerzo computacional introduciendo un sesgo inductivo en la estructura, lo que abre nuevas posibilidades para las arquitecturas de modelos grandes destinadas a tareas de visión generales.

Modelos disponibles, tareas compatibles y modos de funcionamiento#

Esta tabla muestra los modelos disponibles, sus pesos preentrenados específicos, las tareas que admiten y su compatibilidad con distintos modos de funcionamiento, como Entrenamiento, Validación, Inferencia y Exportación. Los modos admitidos se indican con ✅ y los no admitidos, con ❌.

Tipo de modeloPesos preentrenadosTareas compatiblesEntrenamientoValidaciónInferenciaExportar
FastSAM-sFastSAM-s.ptSegmentación de instancias❌✅✅✅
FastSAM-xFastSAM-x.ptSegmentación de instancias❌✅✅✅

Comparación de FastSAM con YOLO#

Aquí comparamos FastSAM-s con las variantes SAM de Meta y los modelos de segmentación de Ultralytics, incluido YOLO26:

ModeloTamaño
(MB)
Parámetros
(M)
Velocidad (CPU)
(ms/im)
Meta SAM-b37593.741703
Meta SAM2-b16280.828867
Meta SAM2-t78.138.923430
MobileSAM40.710.123802
FastSAM-s con backbone YOLOv823.911.858.0
Ultralytics YOLOv8n-seg7.1 (11.0x más pequeño)3.4 (11.4x menos)24.8 (945x más rápido)
Ultralytics YOLO11n-seg6.2 (12.6x más pequeño)2.9 (13.4x menos)24.3 (964x más rápido)
Ultralytics YOLO26n-seg6.7 (11.7x más pequeño)2.7 (14.4x menos)25.2 (930x más rápido)

Esta comparación muestra las diferencias considerables de tamaño y velocidad entre las variantes de SAM y los modelos de segmentación YOLO. Aunque SAM ofrece capacidades únicas de segmentación automática, los modelos YOLO, en particular YOLOv8n-seg, YOLO11n-seg y YOLO26n-seg, son mucho más pequeños, rápidos y eficientes desde el punto de vista computacional.

Las velocidades de SAM se han medido con PyTorch y las de YOLO, con ONNX Runtime. Las pruebas se han realizado en un Apple M4 Air de 2025 con 16 GB de RAM usando torch==2.10.0, ultralytics==8.4.31 y onnxruntime==1.24.4. Para reproducir esta prueba:

Ejemplo
from ultralytics import ASSETS, SAM, YOLO, FastSAM

# Perfilar SAM2-t, SAM2-b, SAM-b, MobileSAM
for file in ["sam_b.pt", "sam2_b.pt", "sam2_t.pt", "mobile_sam.pt"]:
    model = SAM(file)
    model.info()
    model(ASSETS)

# Perfilar FastSAM-s
model = FastSAM("FastSAM-s.pt")
model.info()
model(ASSETS)

# Perfilar modelos YOLO (ONNX)
for file_name in ["yolov8n-seg.pt", "yolo11n-seg.pt", "yolo26n-seg.pt"]:
    model = YOLO(file_name)
    model.info()
    onnx_path = model.export(format="onnx", dynamic=True, nms=False)  # Cabezal sin NMS de YOLO26; no hace nada con YOLOv8/YOLO11
    model = YOLO(onnx_path)
    model(ASSETS)

Ejemplos de uso#

Los modelos FastSAM son fáciles de integrar en tus aplicaciones Python. Ultralytics ofrece tanto una API de Python como comandos de CLI.

Uso de la predicción#

Para segmentar una imagen, usa el método predict como se muestra a continuación:

Ejemplo
from ultralytics import FastSAM

# Define una fuente de inferencia
source = "path/to/bus.jpg"

# Crea un modelo FastSAM
model = FastSAM("FastSAM-s.pt")  # o FastSAM-x.pt

# Ejecuta la inferencia en una imagen
everything_results = model(source, device="cpu", retina_masks=True, imgsz=1024, conf=0.4, iou=0.9)

# Ejecutar inferencia con una indicación de cuadros delimitadores
results = model(source, bboxes=[439, 437, 524, 709])

# Ejecuta la inferencia con una indicación de puntos
results = model(source, points=[[200, 200]], labels=[1])

# Ejecuta la inferencia con indicaciones de texto
results = model(source, texts="a photo of a dog")

# Ejecuta la inferencia a la vez con indicaciones de cuadros delimitadores, puntos y texto
results = model(source, bboxes=[439, 437, 524, 709], points=[[200, 200]], labels=[1], texts="a photo of a dog")

Este fragmento muestra lo sencillo que es cargar un modelo preentrenado y ejecutar una predicción sobre una imagen.

Ejemplo de FastSAMPredictor

Ejecuta la inferencia en una imagen una vez para obtener todos los results segmentados y, a continuación, aplica indicaciones a esos resultados varias veces sin volver a ejecutar la inferencia.

from ultralytics.models.fastsam import FastSAMPredictor

# Crea FastSAMPredictor
overrides = {"conf": 0.25, "task": "segment", "mode": "predict", "model": "FastSAM-s.pt", "save": False, "imgsz": 1024}
predictor = FastSAMPredictor(overrides=overrides)

# Segmenta todo
everything_results = predictor("ultralytics/assets/bus.jpg")

# Inferencia con indicaciones
bbox_results = predictor.prompt(everything_results, bboxes=[[200, 200, 300, 300]])
point_results = predictor.prompt(everything_results, points=[200, 200])
text_results = predictor.prompt(everything_results, texts="a photo of a dog")
Nota

Todos los results devueltos en los ejemplos anteriores son objetos Results que proporcionan acceso a las máscaras predichas y a la imagen de origen.

Uso de la validación#

FastSAM solo admite la detección y segmentación de una única clase de objeto, por lo que reconoce y segmenta todos los objetos como si pertenecieran a la misma clase. Al preparar el conjunto de datos, convierte todos los ID de categoría de los objetos a 0.

La validación del modelo en un conjunto de datos se puede realizar así:

Ejemplo
from ultralytics import FastSAM

# Crea un modelo FastSAM
model = FastSAM("FastSAM-s.pt")  # o FastSAM-x.pt

# Valida el modelo
results = model.val(data="coco8-seg.yaml")

Seguimiento de uso#

Para realizar el seguimiento de objetos en una imagen, usa el método track como se muestra a continuación:

Ejemplo
from ultralytics import FastSAM

# Crea un modelo FastSAM
model = FastSAM("FastSAM-s.pt")  # o FastSAM-x.pt

# Seguimiento con un modelo FastSAM en un vídeo
results = model.track(source="path/to/video.mp4", imgsz=640)

Uso oficial de FastSAM#

FastSAM también está disponible directamente en el repositorio CASIA-LMC-Lab/FastSAM. Aquí tienes un breve resumen de los pasos habituales para usar FastSAM:

Instalación#

  1. Clona el repositorio de FastSAM:

    git clone https://github.com/CASIA-LMC-Lab/FastSAM.git
  2. Crea y activa un entorno Conda con Python 3.9:

    conda create -n FastSAM python=3.9
    conda activate FastSAM
  3. Ve al repositorio clonado e instala los paquetes necesarios:

    cd FastSAM
    pip install -r requirements.txt
  4. Instala el modelo CLIP:

    pip install git+https://github.com/ultralytics/CLIP.git

Ejemplo de uso#

  1. Descarga un punto de control del modelo.

  2. Usa FastSAM para la inferencia. Ejemplos de comandos:

    • Segmenta todos los elementos de una imagen:

      python Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg
    • Segmenta objetos concretos mediante una instrucción de texto:

      python Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg --text_prompt "the yellow dog"
    • Segmenta objetos dentro de un cuadro delimitador (indica las coordenadas del cuadro en formato xywh):

      python Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg --box_prompt "[570,200,230,400]"
    • Segmenta objetos cercanos a puntos concretos:

      python Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg --point_prompt "[[520,360],[620,300]]" --point_label "[1,0]"

Además, puedes probar FastSAM en la demo de Colab de CASIA-LMC-Lab.

Citas y agradecimientos#

Queremos reconocer las importantes contribuciones de los autores de FastSAM al campo de la segmentación de instancias en tiempo real:

Cita
@misc{zhao2023fast,
      title={Fast Segment Anything},
      author={Xu Zhao and Wenchao Ding and Yongqi An and Yinglong Du and Tao Yu and Min Li and Ming Tang and Jinqiao Wang},
      year={2023},
      eprint={2306.12156},
      archivePrefix={arXiv},
      primaryClass={cs.CV}
}

El artículo original de FastSAM está disponible en arXiv. Los autores han publicado su trabajo y puedes acceder al código en GitHub. Agradecemos sus esfuerzos por impulsar el campo y hacer que su trabajo esté al alcance de toda la comunidad.

Preguntas frecuentes#

  • FastSAM, abreviatura de Fast Segment Anything Model, es una solución en tiempo real basada en una red neuronal convolucional (CNN), diseñada para reducir las necesidades computacionales y mantener un alto rendimiento en tareas de segmentación de objetos. A diferencia del Segment Anything Model (SAM), que utiliza una arquitectura más pesada basada en Transformer, FastSAM utiliza Ultralytics YOLOv8-seg para realizar una segmentación de instancias eficiente en dos etapas: segmentación de todas las instancias seguida de selección guiada por indicaciones.

  • FastSAM logra la segmentación en tiempo real al dividir la tarea en dos etapas: segmentación de todas las instancias con YOLOv8-seg y selección guiada por indicaciones. Gracias a la eficiencia computacional de las CNN, FastSAM reduce considerablemente las necesidades computacionales y de recursos, a la vez que mantiene un rendimiento competitivo. Este enfoque en dos etapas permite a FastSAM ofrecer una segmentación rápida y eficiente, adecuada para aplicaciones que requieren resultados inmediatos.

  • FastSAM resulta práctico para diversas tareas de visión artificial que requieren segmentación en tiempo real. Entre sus aplicaciones se incluyen:

    • Automatización industrial para el control y la garantía de calidad
    • Análisis de vídeo en tiempo real para seguridad y vigilancia
    • Vehículos autónomos para la detección y segmentación de objetos
    • Diagnóstico por imagen para tareas de segmentación rápidas y precisas

    Su capacidad para gestionar distintas instrucciones de interacción del usuario hace que FastSAM sea adaptable y flexible en diversos escenarios.

  • Para usar FastSAM para realizar inferencias en Python, puedes seguir este ejemplo:

    from ultralytics import FastSAM
    
    # Define una fuente de inferencia
    source = "path/to/bus.jpg"
    
    # Crea un modelo FastSAM
    model = FastSAM("FastSAM-s.pt")  # o FastSAM-x.pt
    
    # Ejecuta la inferencia en una imagen
    everything_results = model(source, device="cpu", retina_masks=True, imgsz=1024, conf=0.4, iou=0.9)
    
    # Ejecutar inferencia con una indicación de cuadros delimitadores
    results = model(source, bboxes=[439, 437, 524, 709])
    
    # Ejecuta la inferencia con una indicación de puntos
    results = model(source, points=[[200, 200]], labels=[1])
    
    # Ejecuta la inferencia con indicaciones de texto
    results = model(source, texts="a photo of a dog")
    
    # Ejecuta la inferencia a la vez con indicaciones de cuadros delimitadores, puntos y texto
    results = model(source, bboxes=[439, 437, 524, 709], points=[[200, 200]], labels=[1], texts="a photo of a dog")

    Para obtener más información sobre los métodos de inferencia, consulta la sección Uso de Predict de la documentación.

  • FastSAM admite varios tipos de instrucciones para guiar las tareas de segmentación:

    • Instrucción «todo»: genera una segmentación de todos los objetos visibles.
    • Indicaciones de caja delimitadora (BBox): Segmenta objetos dentro de una caja delimitadora especificada. Una caja que no se solapa con ninguna máscara detectada no selecciona nada.
    • Instrucción de texto: usa un texto descriptivo para segmentar los objetos que coincidan con la descripción.
    • Instrucción de punto: segmenta los objetos cercanos a puntos definidos por el usuario.

    Esta flexibilidad permite a FastSAM adaptarse a una amplia variedad de situaciones de interacción con el usuario y aumenta su utilidad en distintas aplicaciones. Para obtener más información sobre cómo usar estas instrucciones, consulta la sección Características principales.

Comentarios26

Haz una pregunta, comparte tus resultados o ayuda a otra persona.

    1. PrashantDixit0GitHub(editado)

      @qinfendekaizhou, can you share the reproducible code for it? Or the reference from where u noticed this.

      In general, post-process time gets increased because of the post-processes involved to show the results, like

      1. NMS
      2. filtering by confidence score/ labels
      3. Scaling results to the original given inputs
      4. Number of objects to be annotated,
      5. Type of annotation, like BB or Segmentation
  1. shahedmomenzadehGitHub

    Hi, I have a question Can I use the generated bbox cordinates by a yolo detection model like yolov11 as bboxes prompt for FastSAM ?

    1. Glenn JocherUltralytics

      @shahedmomenzadeh yes, you can use YOLO detection model-generated bbox coordinates as prompts for FastSAM. The FastSAM documentation shows examples of passing bbox coordinates directly to the model using either the Python API or CLI. Just ensure your coordinates are in XYXY format as shown in the examples.

  2. ismailwaleGitHub

    How can I make an inference of a video using frame by frame in loop using FastSam ?because I tried multiple times making inference directly with video predictor I constantly running out of memory despite setting stream =True since SAM is trying to keep the memory of 2000 frames of the video at ones . I will appreciate any ideal on how to predict and segment the video as a single frame image at every instance and put everything in a loop.

    Similar question win MobileSam

    1. Glenn JocherUltralytics

      @ismailwale to process a video frame by frame and avoid memory overload with FastSAM or MobileSAM, load the video as a frame sequence using a tool like OpenCV. Loop through each frame, run inference on it individually, and clear any cached results to free up memory between frames. For reference on frame-wise usage, consult OpenCV and FastSAM integration. Let me know if you need further clarifications!

    2. llu025GitHub

      Thank you all for your great work! I am having troubles with prompting with a bounding box, it seems the FastSAM model ignores it and detects objects all over the video frames. This is how I obtain the results:

      results = model(
          input_filename,
          device=device,
          imgsz=(736, 1280),
          verbose=False,
          stream=True,
          bboxes=[0, 0, 360, 640],
          retina_masks=True,
          conf=0.4,
          iou=0.9,
      )

      I also tried with bboxes=[[0, 0, 360, 640]], without success. The model should detect objects in the top left quadrant of the video, instead it detects everywhere. Also, it oddly does not raise any error or warnings, both with bboxes as list of integers or bboxes as list of lists of integers.

    3. Glenn JocherUltralytics

      It seems the bounding box prompts aren't being applied as expected. Ensure the bboxes format is correct (e.g., [[x1, y1, x2, y2]] as a list of lists). Additionally, try using the FastSAMPredictor approach for more controlled prompt application, as shown in this example. Let me know if the issue persists!

    4. llu025GitHub

      Thank you @glenn-jocher for the "prompt" response ;-)

      I need to use stream=True since I am working with large videos. I cannot use it coupled with FastSAMPredictor, because it does not support it. My only alternative is to grab frames on my own with OpenCV, is that correct?

      By the way, in your examples in here bboxes is passed as a list of integers, I followed those in the beginning. I see in the examples with FastSAMPredictor that a list of lists is used instead. In any case, I ensured that I was using a list of lists, and it did not work anyway.

      Here's a minimal example of what I am trying to do, i.e., detecting objects in the top left part of the video:

      from ultralytics import FastSAM
      import os
      import ffmpeg
      
      input_filename = "test_video.mp4"
      base_name = os.path.splitext(os.path.basename(input_filename))[0]
      output_filename = os.path.join("output", f"{base_name}.avi")
      
      model = FastSAM("models/FastSAM-x.pt")
      
      process2 = (
          ffmpeg.input(
              "pipe:",
              format="rawvideo",
              pix_fmt="rgb24",
              s="1280x720",
              loglevel="-8",
          )
          .output(
              output_filename,
              pix_fmt="yuv420p",
              vcodec="libx264",
              loglevel="-8",
              crf=17,
          )
          .overwrite_output()
          .run_async(pipe_stdin=True)
      )
      
      results = model(
          input_filename,
          device="cuda",
          imgsz=(736, 1280),
          verbose=False,
          stream=True,
          bboxes=[[0, 0, 360, 640]],
          retina_masks=True,
          conf=0.4,
          iou=0.9,
      )
      
      for result in results:
          frame = result.plot()
          # Save on disk with process2
          process2.stdin.write(frame.tobytes())
      
      process2.stdin.close()
      process2.wait()
    5. Glenn JocherUltralytics

      Thank you for the detailed explanation and example. Yes, you're correct—using OpenCV to manually grab frames is a valid and efficient approach, especially when working with stream=True for large videos, as it avoids memory issues. Regarding bboxes, FastSAM expects a list of lists in the format [[x1, y1, x2, y2]]. If this still doesn't work as intended, please ensure your bounding box coordinates are correct and within the frame dimensions. Let us know if you encounter any further issues!

    6. llu025GitHub

      I still encounter the same issue. I used bboxes=[[20, 20, 500, 500]] just to be 100% sure the coordinates are within the the frame dimensions (1280x720), nothing changed. Since I have to grab frames with OpenCV anyway, I will just crop them myself, but I am quite sure this option is not working as intended.

    7. Glenn JocherUltralytics

      @llu025 thank you for the update. If you’re certain the bboxes parameter is properly configured and still not working as intended, cropping frames manually with OpenCV before passing them to the model is indeed a reliable workaround. It may also be worth checking the latest FastSAM updates or reporting this as a potential issue to ensure the bounding box prompt functionality is reviewed. Let us know if you need further assistance!

  3. chongkuiqiGitHub

    Thanks for your great work! I'm using FastSAM-x with bboxes prompt, the original image shape is [720, 1280], and I set 'imgsz' 1024. However, the results mask shape is [576, 1024], but I remembered in ultralytics-8.2.10, I can get masks with the same shape as the original image. May I ask why this change happened ?

    1. Glenn JocherUltralytics

      @feiwenxiong fastSAM should support multiple boxes. If you're experiencing limitations, please ensure your input format is correct. For further assistance, you might want to check the latest updates or documentation.

  4. YuechengLiuGitHub

    Thanks the authors for the great work!

    I'm using FastSAM-x for instance segmentation (bboxes as the prompt), but I find that the shape of the predicted masks mismatch with the bounding box number. (e.g. the model takes 18 bboxes as input, but the shape of the predicted mask is (17, H, W)) . I tried to set conf=0.01 and iou=0.999, but it doesn't work. How can I solve that? Thanks!

    1. Glenn JocherUltralytics

      @YuechengLiu thank you for your kind words! The issue you're experiencing might be due to a mismatch in the bounding box prompts and the segmentation results. Please ensure you're using the latest version of the FastSAM model. If the problem persists, consider checking the input format and the bounding box coordinates. For further assistance, you can refer to the FastSAM documentation: https://docs.ultralytics.com/models/fast-sam/.

    2. YuechengLiuGitHub

      Thanks for your kind reply! The bounding boxes I'm using are predicted by yolov10x (result.boxes.xyxy), so I think the input format might be right. I also tried the same bounding boxes for mobile_sam, and the output dimension is as expected (same as the input dimension). The problem does not always occur. Do you have any idea about that? Thanks!

    3. Glenn JocherUltralytics

      Thanks for confirming you're using the latest version. Given that the issue is intermittent, it might be related to the specific bounding boxes or the image content. Please try running the model with a different set of bounding boxes or images to see if the issue persists. If it does, consider opening an issue on the GitHub repository with detailed information for further investigation.

  5. nguyenvandang1998GitHub

    Hi! I am using the FastSAM model and trying to obtain information about the bounding box and mask image of the object, but I don't know how to do it. I hope you can help me. Thank you very much!!

    1. nguyenvandang1998GitHub

      Currently, I can obtain information about the bounding box, but I still don't know how to get the mask image!!

    2. Glenn JocherUltralytics(editado)

      Hi there! 🙌 To extract both bounding boxes and mask images using the FastSAM model, you would typically work with the results object returned by the model's prediction method. For the bounding boxes, you can access them directly as shown in the documentation or examples provided. For the mask images, since FastSAM is designed for real-time segmentation, the results should also include segmentation masks corresponding to detected objects.

      Here's a simplified way to access both:

      from ultralytics import FastSAM
      
      # Define your image source
      source = 'path/to/your/image.jpg'
      
      # Load the FastSAM model (ensure you've chosen the correct model path)
      model = FastSAM('FastSAM-s.pt')  # or another appropriate model
      
      # Perform inference
      results = model(source)
      
      # Accessing bounding boxes (assuming XYXY format)
      boxes = results[0].boxes.xyxy
      
      # Accessing segmentation masks
      # The masks are directly associated with detected objects in the results
      masks = results[0].masks
      
      # To visualize or further process masks and boxes, you would iterate through these objects

      To visualize or save the masks, you'd typically iterate over the masks object, and each mask can be processed according to your requirements (e.g., overlaying on the original image or saving as separate mask images).

      Remember, the exact attribute names (boxes, masks) and methods might vary based on the model output specification, so it's always good to refer to the specific documentation or example codes for guidance.

      Hope this helps! Let us know if you have more questions. 😊

      2