Başla

Hızlı Segment Anything Modeli (FastSAM)

Fast Segment Anything Model (FastSAM), Segment Anything görevi için geliştirilmiş, gerçek zamanlı ve CNN tabanlı bir çözümdür. Bu görev, çeşitli kullanıcı etkileşimi istemlerine göre bir görüntüdeki herhangi bir nesneyi segmentlere ayırmak üzere tasarlanmıştır. FastSAM, rekabetçi performansını korurken hesaplama gereksinimlerini önemli ölçüde azaltır; bu da onu çeşitli görüntü işleme görevleri için pratik bir seçenek hâline getirir.



İzle: Ultralytics ile FastSAM Kullanarak Nesne Takibi

Model Mimarisi#

Hızlı Segment Anything Modeli (FastSAM) mimarisine genel bakış

Genel Bakış#

FastSAM, yüksek hesaplama kaynağı gereksinimleri olan ağır bir Transformer modeli olan Segment Anything Model'in (SAM) sınırlamalarını gidermek üzere tasarlanmıştır. FastSAM, segment anything görevini art arda gelen iki aşamaya ayırır: tüm örneklerin segmentasyonu ve istem kılavuzluğunda seçim. İlk aşamada YOLOv8-seg, görüntüdeki tüm örneklerin segmentasyon maskelerini oluşturur. İkinci aşamada ise isteme karşılık gelen ilgi bölgesini verir.

Temel Özellikler#

  1. Gerçek Zamanlı Çözüm: CNN'lerin hesaplama verimliliğinden yararlanan FastSAM, segment anything görevi için gerçek zamanlı bir çözüm sunar ve hızlı sonuç gerektiren endüstriyel uygulamalar için değer taşır.

  2. Verimlilik ve Performans: FastSAM, SAM ile karşılaştırılabilir bir performans sunarken hesaplama ve kaynak gereksinimlerini önemli ölçüde azaltarak gerçek zamanlı uygulamalara olanak tanır.

  3. İstem Kılavuzluğunda Segmentasyon: FastSAM, çeşitli kullanıcı etkileşimi istemleri doğrultusunda görüntüdeki herhangi bir nesneyi segmentlere ayırabilir; böylece farklı senaryolarda esneklik ve uyarlanabilirlik sağlar.

  4. YOLOv8-seg Tabanlı: FastSAM, örnek segmentasyonu dalına sahip bir nesne algılayıcısı olan YOLOv8-seg tabanlıdır. Bu sayede görüntüdeki tüm örneklerin segmentasyon maskelerini etkili biçimde oluşturabilir.

  5. Kıyaslamalarda Rekabetçi Sonuçlar: FastSAM, MS COCO üzerindeki nesne önerisi görevinde tek bir NVIDIA RTX 3090'da SAM'den çok daha hızlı çalışırken yüksek skorlar elde ederek verimliliğini ve kapasitesini gösterir.

  6. Pratik Uygulamalar: Bu yaklaşım, birçok görüntü işleme görevi için pratik bir çözüm sunar ve önceki segment anything yöntemlerinden onlarca ila yüzlerce kat daha hızlı çalışır.

  7. Model Sıkıştırmanın Uygulanabilirliği: FastSAM, yapıya yapay bir öncül ekleyerek hesaplama yükünü önemli ölçüde azaltabilecek bir yaklaşımın uygulanabilirliğini gösterir. Böylece genel görüntü işleme görevleri için büyük model mimarilerinde yeni olanakların önünü açar.

Kullanılabilir Modeller, Desteklenen Görevler ve Çalışma Modları#

Bu tabloda, kullanılabilir modeller; belirli önceden eğitilmiş ağırlıkları, destekledikleri görevler ve Eğitim, Doğrulama, Çıkarım ve Dışa Aktarma gibi farklı çalışma modlarıyla uyumluluklarıyla birlikte sunulmuştur. Desteklenen modlar ✅, desteklenmeyen modlar ise ❌ ile gösterilir.

Model TürüÖnceden Eğitilmiş AğırlıklarDesteklenen GörevlerEğitimDoğrulamaÇıkarımDışa aktar
FastSAM-sFastSAM-s.ptÖrnek Segmentasyonu❌✅✅✅
FastSAM-xFastSAM-x.ptÖrnek Segmentasyonu❌✅✅✅

FastSAM ve YOLO Karşılaştırması#

Burada FastSAM-s modelini, Meta'nın SAM varyantları ve YOLO26 dahil Ultralytics segmentasyon modelleriyle karşılaştırıyoruz:

ModelBoyut
(MB)
Parametreler
(M)
Hız (CPU)
(ms/görüntü)
Meta SAM-b37593.741703
Meta SAM2-b16280.828867
Meta SAM2-t78.138.923430
MobileSAM40.710.123802
YOLOv8 omurgalı FastSAM-s23.911.858.0
Ultralytics YOLOv8n-seg7.1 (11.0 kat daha küçük)3.4 (11.4 kat daha az)24.8 (945 kat daha hızlı)
Ultralytics YOLO11n-seg6.2 (12.6 kat daha küçük)2.9 (13.4 kat daha az)24.3 (964 kat daha hızlı)
Ultralytics YOLO26n-seg6.7 (11.7 kat daha küçük)2.7 (14.4 kat daha az)25.2 (930 kat daha hızlı)

Bu karşılaştırma, SAM varyantları ile YOLO segmentasyon modelleri arasındaki model boyutu ve hız farklarının ne kadar büyük olduğunu gösteriyor. SAM, kendine özgü otomatik segmentasyon yetenekleri sunarken YOLO modelleri, özellikle YOLOv8n-seg, YOLO11n-seg ve YOLO26n-seg, önemli ölçüde daha küçük, daha hızlı ve hesaplama açısından daha verimlidir.

SAM hızları PyTorch, YOLO hızları ise ONNX Runtime kullanılarak ölçülmüştür. Testler, 16 GB RAM'e sahip 2025 Apple M4 Air üzerinde torch==2.10.0, ultralytics==8.4.31 ve onnxruntime==1.24.4 kullanılarak gerçekleştirilmiştir. Bu testi tekrarlamak için:

Örnek
from ultralytics import ASSETS, SAM, YOLO, FastSAM

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

# FastSAM-s profili oluştur
model = FastSAM("FastSAM-s.pt")
model.info()
model(ASSETS)

# YOLO modellerinin profilini çıkar (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)  # YOLO26 NMS içermeyen başlık; YOLOv8/YOLO11 için işlem yapmaz
    model = YOLO(onnx_path)
    model(ASSETS)

Kullanım Örnekleri#

FastSAM modellerini Python uygulamalarına kolayca entegre edebilirsin. Ultralytics hem Python API'si hem de CLI komutları sunar.

Tahmin Kullanımı#

Bir görüntüyü segmentlere ayırmak için aşağıda gösterildiği gibi predict yöntemini kullan:

Örnek
from ultralytics import FastSAM

# Çıkarım kaynağını tanımla
source = "path/to/bus.jpg"

# Bir FastSAM modeli oluştur
model = FastSAM("FastSAM-s.pt")  # veya FastSAM-x.pt

# Bir görüntü üzerinde çıkarım yap
everything_results = model(source, device="cpu", retina_masks=True, imgsz=1024, conf=0.4, iou=0.9)

# bbox istemiyle çıkarım çalıştır
results = model(source, bboxes=[439, 437, 524, 709])

# Nokta istemiyle çıkarım yap
results = model(source, points=[[200, 200]], labels=[1])

# Metin istemleriyle çıkarım yap
results = model(source, texts="a photo of a dog")

# bbox'lar, noktalar ve metin istemlerini aynı anda kullanarak çıkarım yap
results = model(source, bboxes=[439, 437, 524, 709], points=[[200, 200]], labels=[1], texts="a photo of a dog")

Bu kod parçası, önceden eğitilmiş bir modeli yüklemenin ve bir görüntü üzerinde tahmin yürütmenin ne kadar kolay olduğunu gösterir.

FastSAMPredictor örneği

Tüm segment results sonuçlarını almak için bir görüntü üzerinde çıkarımı bir kez çalıştır; ardından çıkarımı yeniden çalıştırmadan bu sonuçlara birden çok kez istem uygula.

from ultralytics.models.fastsam import FastSAMPredictor

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

# Her şeyi segmente ayır
everything_results = predictor("ultralytics/assets/bus.jpg")

# İstem çıkarımı
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")
Not

Yukarıdaki örneklerde döndürülen results nesnelerinin tümü, tahmin edilen maskelere ve kaynak görüntüye erişim sağlayan Results nesneleridir.

Doğrulama Kullanımı#

FastSAM, yalnızca tek bir nesne sınıfının algılanmasını ve segmentasyonunu destekler; bu nedenle tüm nesneleri aynı sınıfa aitmiş gibi tanır ve segmentlere ayırır. Veri kümesini hazırlarken tüm nesne kategorisi kimliklerini 0'a dönüştür.

Bir modelin veri kümesi üzerinde doğrulanması şu şekilde yapılabilir:

Örnek
from ultralytics import FastSAM

# Bir FastSAM modeli oluştur
model = FastSAM("FastSAM-s.pt")  # veya FastSAM-x.pt

# Modeli doğrula
results = model.val(data="coco8-seg.yaml")

Takip Kullanımı#

Bir görüntüde nesne takibi yapmak için aşağıda gösterildiği gibi track yöntemini kullan:

Örnek
from ultralytics import FastSAM

# Bir FastSAM modeli oluştur
model = FastSAM("FastSAM-s.pt")  # veya FastSAM-x.pt

# Bir FastSAM modeliyle videoda takip yap
results = model.track(source="path/to/video.mp4", imgsz=640)

FastSAM Resmî Kullanımı#

FastSAM, CASIA-LMC-Lab/FastSAM deposundan doğrudan da kullanılabilir. FastSAM'ı kullanırken izleyebileceğin tipik adımlara kısaca göz atalım:

Kurulum#

  1. FastSAM deposunu klonla:

    git clone https://github.com/CASIA-LMC-Lab/FastSAM.git
  2. Python 3.9 ile bir Conda ortamı oluştur ve etkinleştir:

    conda create -n FastSAM python=3.9
    conda activate FastSAM
  3. Klonladığın depoya git ve gerekli paketleri yükle:

    cd FastSAM
    pip install -r requirements.txt
  4. CLIP modelini yükle:

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

Kullanım Örneği#

  1. Bir model kontrol noktası indir.

  2. Çıkarım için FastSAM'ı kullan. Örnek komutlar:

    • Bir görüntüdeki her şeyi bölütle:

      python Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg
    • Metin istemi kullanarak belirli nesneleri bölütle:

      python Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg --text_prompt "the yellow dog"
    • Bir sınırlayıcı kutu içindeki nesneleri bölütle (kutu koordinatlarını xywh biçiminde ver):

      python Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg --box_prompt "[570,200,230,400]"
    • Belirli noktaların yakınındaki nesneleri bölütle:

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

Ayrıca FastSAM'ı CASIA-LMC-Lab Colab demosu üzerinden deneyebilirsin.

Atıflar ve Teşekkürler#

Gerçek zamanlı örnek bölütleme alanındaki önemli katkılarından dolayı FastSAM yazarlarına teşekkür ederiz:

Atıf
@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}
}

Özgün FastSAM makalesine arXiv üzerinden ulaşabilirsin. Yazarlar çalışmalarını herkese açık hâle getirdi ve kod tabanına GitHub üzerinden erişilebilir. Alandaki ilerlemeye katkı sağlama ve çalışmalarını daha geniş topluluğun erişimine açma çabalarını takdir ediyoruz.

Sık Sorulan Sorular#

  • Fast Segment Anything Model'in kısaltması olan FastSAM, nesne segmentasyonu görevlerinde yüksek performansını korurken hesaplama gereksinimlerini azaltmak üzere tasarlanmış, gerçek zamanlı ve evrişimli sinir ağı (CNN) tabanlı bir çözümdür. Daha ağır Transformer tabanlı bir mimari kullanan Segment Anything Model'in (SAM) aksine FastSAM, verimli örnek segmentasyonu için Ultralytics YOLOv8-seg modelini iki aşamada kullanır: önce tüm örneklerin segmentasyonu, ardından istem kılavuzluğunda seçim.

  • FastSAM, segmentasyon görevini YOLOv8-seg ile tüm örneklerin segmentasyonu ve istem kılavuzluğunda seçim aşamalarına ayırarak gerçek zamanlı segmentasyon sağlar. CNN'lerin hesaplama verimliliğinden yararlanan FastSAM, rekabetçi performansını korurken hesaplama ve kaynak gereksinimlerini önemli ölçüde azaltır. Bu iki aşamalı yaklaşım, hızlı sonuç gerektiren uygulamalara uygun, hızlı ve verimli segmentasyon sağlar.

  • FastSAM, gerçek zamanlı bölütleme performansı gerektiren çeşitli bilgisayarlı görü görevlerinde kullanışlıdır. Uygulama alanları şunlardır:

    • Kalite kontrolü ve güvencesi için endüstriyel otomasyon
    • Güvenlik ve gözetim için gerçek zamanlı video analizi
    • Nesne algılama ve bölütleme için otonom araçlar
    • Hassas ve hızlı bölütleme görevleri için tıbbi görüntüleme

    Farklı kullanıcı etkileşimi istemlerini işleyebilmesi, FastSAM'ı çeşitli senaryolara uyarlanabilir ve esnek hâle getirir.

  • Python'da çıkarım için FastSAM'ı aşağıdaki örneği izleyerek kullanabilirsin:

    from ultralytics import FastSAM
    
    # Çıkarım kaynağını tanımla
    source = "path/to/bus.jpg"
    
    # Bir FastSAM modeli oluştur
    model = FastSAM("FastSAM-s.pt")  # veya FastSAM-x.pt
    
    # Bir görüntü üzerinde çıkarım yap
    everything_results = model(source, device="cpu", retina_masks=True, imgsz=1024, conf=0.4, iou=0.9)
    
    # bbox istemiyle çıkarım çalıştır
    results = model(source, bboxes=[439, 437, 524, 709])
    
    # Nokta istemiyle çıkarım yap
    results = model(source, points=[[200, 200]], labels=[1])
    
    # Metin istemleriyle çıkarım yap
    results = model(source, texts="a photo of a dog")
    
    # bbox'lar, noktalar ve metin istemlerini aynı anda kullanarak çıkarım yap
    results = model(source, bboxes=[439, 437, 524, 709], points=[[200, 200]], labels=[1], texts="a photo of a dog")

    Çıkarım yöntemleri hakkında daha fazla bilgi için belgelendirmedeki Tahmin Kullanımı bölümüne göz at.

  • FastSAM, bölütleme görevlerini yönlendirmek için birden çok istem türünü destekler:

    • Her Şey İstemi: Görüntüde görünen tüm nesneler için bölütleme üretir.
    • Sınırlayıcı Kutu (BBox) İstemi: Belirtilen sınırlayıcı kutu içindeki nesneleri segmentlere ayırır. Algılanan hiçbir maskeyle örtüşmeyen bir kutu hiçbir şey seçmez.
    • Metin İstemi: Açıklamayla eşleşen nesneleri bölütlemek için tanımlayıcı bir metin kullanır.
    • Nokta İstemi: Kullanıcı tarafından tanımlanan belirli noktaların yakınındaki nesneleri bölütler.

    Bu esneklik, FastSAM'ın çok çeşitli kullanıcı etkileşimi senaryolarına uyum sağlamasına ve farklı uygulamalardaki kullanışlılığını artırmasına olanak tanır. Bu istemleri kullanma hakkında daha fazla bilgi için Temel Özellikler bölümüne bak.

Yorumlar26

Bir soru sor, sonuçlarını paylaş veya başka birine yardım et.

    1. PrashantDixit0GitHub(düzenlendi)

      @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(düzenlendi)

      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