Fast Segment Anything Model (FastSAM)

Fast Segment Anything Model (FastSAM)은 Segment Anything 작업을 위한 새롭고 실시간 처리가 가능한 CNN 기반 솔루션입니다. 이 작업은 다양한 사용자 상호작용 프롬프트를 기반으로 이미지 내의 모든 객체를 분할하도록 설계되었습니다. FastSAM은 성능을 유지하면서 계산 요구량을 크게 줄여 다양한 비전 작업에서 실용적인 선택지가 됩니다.



Watch: Object Tracking using FastSAM with Ultralytics

모델 아키텍처

Fast Segment Anything Model (FastSAM) 아키텍처 개요

개요

FastSAM is designed to address the limitations of the Segment Anything Model (SAM), a heavy Transformer model with substantial computational resource requirements. The FastSAM decouples the segment anything task into two sequential stages: all-instance segmentation and prompt-guided selection. The first stage uses YOLOv8-seg to produce the segmentation masks of all instances in the image. In the second stage, it outputs the region-of-interest corresponding to the prompt.

주요 특징

  1. 실시간 솔루션: CNN의 계산 효율성을 활용하는 FastSAM은 segment anything 작업을 위한 실시간 솔루션을 제공하며, 빠른 결과가 필요한 산업용 애플리케이션에 유용합니다.

  2. 효율성 및 성능: FastSAM은 성능 품질을 저하시키지 않으면서 계산 및 자원 요구량을 크게 줄여줍니다. SAM과 비교 가능한 성능을 달성하면서도 계산 자원을 대폭 절감하여 실시간 애플리케이션을 가능하게 합니다.

  3. 프롬프트 기반 분할: FastSAM은 다양한 사용자 상호작용 프롬프트의 안내를 받아 이미지 내 모든 객체를 분할할 수 있으며, 여러 시나리오에서 유연성과 적응성을 제공합니다.

  4. YOLOv8-seg 기반: FastSAM은 인스턴스 분할 브랜치를 갖춘 객체 탐지기인 YOLOv8-seg를 기반으로 합니다. 이를 통해 이미지 내 모든 인스턴스의 분할 마스크를 효과적으로 생성할 수 있습니다.

  5. 벤치마크에서의 경쟁력 있는 결과: MS COCO의 객체 제안 작업에서 FastSAM은 단일 NVIDIA RTX 3090 환경에서 SAM보다 훨씬 빠른 속도로 높은 점수를 기록하며 그 효율성과 역량을 입증했습니다.

  6. 실용적인 애플리케이션: 이 접근 방식은 기존 방식보다 수십 또는 수백 배 빠른 속도로 수많은 비전 작업에 새로운 실용적 솔루션을 제공합니다.

  7. 모델 압축 타당성: FastSAM은 구조에 인공적인 사전 지식(prior)을 도입하여 계산 노력을 크게 줄일 수 있는 경로의 타당성을 입증하며, 일반 비전 작업을 위한 대형 모델 아키텍처의 새로운 가능성을 열어줍니다.

사용 가능한 모델, 지원되는 작업 및 작동 모드

이 표는 특정 사전 학습된 가중치를 가진 사용 가능한 모델, 해당 모델이 지원하는 작업, 그리고 Inference, Validation, Training, Export와 같은 다양한 작동 모드와의 호환성을 나타내며, 지원되는 모드는 ✅ 이모지로, 지원되지 않는 모드는 ❌ 이모지로 표시되어 있습니다.

모델 유형사전 학습된 가중치지원 작업추론검증학습내보내기 (Export)
FastSAM-sFastSAM-s.pt인스턴스 세그멘테이션
FastSAM-xFastSAM-x.pt인스턴스 세그멘테이션

FastSAM과 YOLO 비교

여기에서는 가장 작은 SAM2-t 변형을 포함한 Meta의 SAM 2 모델을 YOLO26n-seg를 포함한 Ultralytics 분할 모델과 비교합니다:

모델크기
(MB)
매개변수
(M)
속도 (CPU)
(ms/im)
Meta SAM-b37593.741703
Meta SAM2-b16280.828867
Meta SAM2-t78.138.923430
MobileSAM40.710.123802
FastSAM-s with YOLOv8 backbone23.911.858.0
Ultralytics YOLOv8n-seg7.1 (11.0배 더 작음)3.4 (11.4배 더 가벼움)24.8 (945배 더 빠름)
Ultralytics YOLO11n-seg6.2 (12.6배 더 작음)2.9 (13.4배 더 가벼움)24.3 (964배 더 빠름)
Ultralytics YOLO26n-seg6.7 (11.7배 더 작음)2.7 (14.4배 더 가벼움)25.2 (930배 더 빠름)

이 비교는 SAM 변형 모델들과 YOLO 세그멘테이션 모델 간의 모델 크기 및 속도 차이를 보여줍니다. SAM은 독보적인 자동 세그멘테이션 기능을 제공하지만, YOLO 모델, 특히 YOLOv8n-seg, YOLO11n-seg 및 YOLO26n-seg는 훨씬 더 작고 빠르며 계산 효율성이 뛰어납니다.

SAM 속도는 PyTorch로 측정되었으며, YOLO 속도는 ONNX Runtime으로 측정되었습니다. 테스트는 16GB RAM이 탑재된 2025 Apple M4 Air에서 torch==2.10.0, ultralytics==8.4.31, onnxruntime==1.24.4를 사용하여 실행되었습니다. 이 테스트를 재현하려면:

예시
from ultralytics import ASSETS, SAM, YOLO, FastSAM

# Profile 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)

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

# Profile YOLO models (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)
    model = YOLO(onnx_path)
    model(ASSETS)

사용 예시

FastSAM 모델은 Python 애플리케이션에 쉽게 통합할 수 있습니다. Ultralytics는 개발을 간소화하기 위해 사용자 친화적인 Python API 및 CLI 명령어를 제공합니다.

예측(Predict) 사용법

이미지에서 object detection을 수행하려면 아래와 같이 predict 메서드를 사용하십시오:

예시
from ultralytics import FastSAM

# Define an inference source
source = "path/to/bus.jpg"

# Create a FastSAM model
model = FastSAM("FastSAM-s.pt")  # or FastSAM-x.pt

# Run inference on an image
everything_results = model(source, device="cpu", retina_masks=True, imgsz=1024, conf=0.4, iou=0.9)

# Run inference with bboxes prompt
results = model(source, bboxes=[439, 437, 524, 709])

# Run inference with points prompt
results = model(source, points=[[200, 200]], labels=[1])

# Run inference with texts prompt
results = model(source, texts="a photo of a dog")

# Run inference with bboxes and points and texts prompt at the same time
results = model(source, bboxes=[439, 437, 524, 709], points=[[200, 200]], labels=[1], texts="a photo of a dog")

이 코드 조각은 사전 학습된 모델을 로드하고 이미지에 대해 예측을 실행하는 간편함을 보여줍니다.

FastSAMPredictor 예제

이 방식을 사용하면 이미지에 대해 추론을 실행하여 모든 분할 results를 한 번 얻은 다음, 추론을 여러 번 실행할 필요 없이 프롬프트 추론을 여러 번 실행할 수 있습니다.

from ultralytics.models.fastsam import FastSAMPredictor

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

# Segment everything
everything_results = predictor("ultralytics/assets/bus.jpg")

# Prompt inference
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")
참고

위 예시에서 반환된 모든 results는 예측된 마스크와 원본 이미지에 쉽게 액세스할 수 있는 Results 객체입니다.

검증(Val) 사용법

데이터셋에 대한 모델 검증은 다음과 같이 수행할 수 있습니다:

예시
from ultralytics import FastSAM

# Create a FastSAM model
model = FastSAM("FastSAM-s.pt")  # or FastSAM-x.pt

# Validate the model
results = model.val(data="coco8-seg.yaml")

FastSAM은 단일 클래스 객체의 탐지 및 분할만 지원한다는 점을 유의하십시오. 즉, 모든 객체를 동일한 클래스로 인식하고 분할합니다. 따라서 데이터셋을 준비할 때 모든 객체 카테고리 ID를 0으로 변환해야 합니다.

추적(Track) 사용법

이미지에서 객체 추적을 수행하려면 아래와 같이 track 메서드를 사용하십시오:

예시
from ultralytics import FastSAM

# Create a FastSAM model
model = FastSAM("FastSAM-s.pt")  # or FastSAM-x.pt

# Track with a FastSAM model on a video
results = model.track(source="path/to/video.mp4", imgsz=640)

FastSAM 공식 사용법

FastSAM은 https://github.com/CASIA-IVA-Lab/FastSAM 저장소에서도 직접 이용할 수 있습니다. FastSAM 사용을 위한 일반적인 단계는 다음과 같습니다:

설치

  1. FastSAM 저장소를 복제합니다:

    git clone https://github.com/CASIA-IVA-Lab/FastSAM.git
  2. Python 3.9로 Conda 환경을 생성하고 활성화합니다:

    conda create -n FastSAM python=3.9
    conda activate FastSAM
  3. 복제된 저장소로 이동하여 필요한 패키지를 설치합니다:

    cd FastSAM
    pip install -r requirements.txt
  4. CLIP 모델을 설치합니다:

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

사용 예시

  1. 모델 체크포인트를 다운로드합니다.

  2. 추론을 위해 FastSAM을 사용합니다. 명령어 예시:

    • 이미지의 모든 항목 분할:

      python Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg
    • 텍스트 프롬프트를 사용하여 특정 객체 분할:

      python Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg --text_prompt "the yellow dog"
    • bounding box 내의 객체 분할 (xywh 형식으로 상자 좌표 제공):

      python Inference.py --model_path ./weights/FastSAM.pt --img_path ./images/dogs.jpg --box_prompt "[570,200,230,400]"
    • 특정 지점 근처의 객체 분할:

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

또한 CASIA-IVA-Lab의 Colab 데모를 통해 FastSAM을 체험해 볼 수 있습니다.

인용 및 감사의 글

실시간 인스턴스 분할 분야에 크게 기여한 FastSAM 저자들에게 감사를 표합니다:

인용
  @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}
  }

원본 FastSAM 논문은 arXiv에서 확인할 수 있습니다. 저자들은 연구 결과를 공개했으며, 코드베이스는 GitHub에서 접근할 수 있습니다. 이 분야를 발전시키고 연구 성과를 더 넓은 커뮤니티가 활용할 수 있도록 노력해 준 점에 감사합니다.

FAQ

FastSAM이란 무엇이며 SAM과 어떻게 다른가요?

FastSAM(Fast Segment Anything Model)은 객체 분할 작업에서 고성능을 유지하면서 계산 요구량을 줄이도록 설계된 실시간 convolutional neural network (CNN) 기반 솔루션입니다. 무거운 Transformer 기반 아키텍처를 사용하는 Segment Anything Model (SAM)과 달리, FastSAM은 효율적인 인스턴스 분할을 위해 Ultralytics YOLOv8-seg를 활용하며 전체 인스턴스 분할 후 프롬프트 기반 선택이라는 두 단계로 작동합니다.

FastSAM은 어떻게 실시간 분할 성능을 달성하나요?

FastSAM은 YOLOv8-seg를 통한 전체 인스턴스 분할과 프롬프트 기반 선택 단계로 분할 작업을 분리하여 실시간 분할을 달성합니다. CNN의 계산 효율성을 활용함으로써, FastSAM은 경쟁력 있는 성능을 유지하면서도 계산 및 자원 요구량을 크게 줄입니다. 이러한 2단계 접근 방식을 통해 FastSAM은 빠른 결과가 필요한 애플리케이션에 적합한 신속하고 효율적인 분할 기능을 제공합니다.

FastSAM의 실용적인 애플리케이션은 무엇인가요?

FastSAM은 실시간 분할 성능이 필요한 다양한 computer vision 작업에 실용적입니다. 애플리케이션은 다음과 같습니다:

  • 품질 관리 및 보증을 위한 산업 자동화
  • 보안 및 감시를 위한 실시간 비디오 분석
  • 객체 탐지 및 분할을 위한 Autonomous vehicles
  • 정밀하고 빠른 분할 작업을 위한 의료 영상

다양한 사용자 상호작용 프롬프트를 처리할 수 있는 능력 덕분에 FastSAM은 여러 시나리오에 적응 가능하고 유연합니다.

Python에서 추론을 위해 FastSAM 모델을 어떻게 사용하나요?

Python에서 추론을 위해 FastSAM을 사용하려면 아래 예제를 따라 할 수 있습니다:

from ultralytics import FastSAM

# Define an inference source
source = "path/to/bus.jpg"

# Create a FastSAM model
model = FastSAM("FastSAM-s.pt")  # or FastSAM-x.pt

# Run inference on an image
everything_results = model(source, device="cpu", retina_masks=True, imgsz=1024, conf=0.4, iou=0.9)

# Run inference with bboxes prompt
results = model(source, bboxes=[439, 437, 524, 709])

# Run inference with points prompt
results = model(source, points=[[200, 200]], labels=[1])

# Run inference with texts prompt
results = model(source, texts="a photo of a dog")

# Run inference with bboxes and points and texts prompt at the same time
results = model(source, bboxes=[439, 437, 524, 709], points=[[200, 200]], labels=[1], texts="a photo of a dog")

추론 방법에 대한 자세한 내용은 문서의 Predict Usage 섹션을 확인하십시오.

FastSAM은 분할 작업을 위해 어떤 유형의 프롬프트를 지원하나요?

FastSAM은 분할 작업을 안내하기 위해 여러 프롬프트 유형을 지원합니다:

  • Everything Prompt: 보이는 모든 객체에 대한 분할을 생성합니다.
  • Bounding Box (BBox) Prompt: 지정된 경계 상자 내의 객체를 분할합니다.
  • Text Prompt: 묘사된 텍스트를 사용하여 설명과 일치하는 객체를 분할합니다.
  • Point Prompt: 사용자 정의 지점 근처의 객체를 분할합니다.

이러한 유연성 덕분에 FastSAM은 광범위한 사용자 상호작용 시나리오에 적응할 수 있으며 다양한 애플리케이션에서 유용성을 높입니다. 이러한 프롬프트 사용에 대한 자세한 정보는 Key Features 섹션을 참조하십시오.

댓글