🧠 What is SAM?
Studying 『Segment Anything』 (ICCV, 2023)
📖 Paper Title: Segment Anything
✍️ Authors: Meta AI Research (Kirillov, Alexey et al.)
🌟 One-line Summary: A general-purpose segmentation model that can segment anything, in any image, from any prompt!
📚 Key Idea
- SAM stands for Segment Anything Model
- Unlike traditional segmentation models,
- SAM is a universal segmentation AI that can extract any object using a single pre-trained model
- Without predefined classes, SAM can segment targets from user prompts
- It’s often called the “GPT for Segmentation” due to its generalization ability
🔍 Background of the SAM Research
- The era of Foundation Models:
- Language models work well with large-scale data
- In vision, CLIP, ALIGN, and image encoders have emerged
- But vision segmentation lacks data diversity
- Research Goal: Build a foundation model for image segmentation
- Three key challenges: a. Task: What segmentation task to define? b. Model: What architecture to use? c. Data: How to collect it?
🎯 The Task Definition in SAM
- Limitations of existing segmentation models:
- Rely on predefined classes
- Require labelled data
- Need fine-tuning for new objects
- Need for Prompt-based, Open-Vocabulary segmentation:
- With multimodal models like CLIP, now we want:
- Models that can segment user-defined targets using text, point, box prompts
👉 So SAM was defined as a “segment-anything” universal segmentation system
⚙️ SAM Model Architecture
Component | Description |
---|
Image Encoder | Encodes entire image into a fixed embedding (done once) |
Prompt Encoder | Encodes prompts like points, boxes, masks |
Mask Decoder | Combines image & prompt embeddings to predict segmentation mask |
Components in Detail
- Image Encoder (ViT-H, MAE pre-trained)
- Uses ViT with Masked Autoencoder (MAE) training
- Produces rich visual representation
- Image embeddings are reused for multiple prompts
- Prompt Encoder
- Handles two types of inputs:
Type | Example | Encoding | Notes |
---|
Sparse | Point, Box, Text | Position + learned embeddings / CLIP text encoder | Text uses CLIP text encoder |
Dense | Mask | Convolution + element-wise sum with image embedding | Used for dense prompts like masks |
- Mask Decoder
- Core logic that fuses prompt and image to output the final mask
Step | Description |
---|
1. Input | Image Embedding + Prompt Embedding + Output Token |
2. Decoder Blocks ×2 | Transformer decoder variant + self & cross attention |
3. Upsampling | Upsamples decoder output using image embedding |
4. Dynamic Prediction | MLP → Linear classifier to produce per-pixel FG probabilities |
5. Output | Generates 3 mask candidates with confidence scores (to resolve ambiguity) |
🏗️ SA-1B Dataset and the Data Engine
- SA-1B: The largest segmentation dataset ever, built by Meta for SAM
- Contains 11M images and over 1.1B masks
- 400× more masks than prior datasets
- ✅ Fully automatic annotation, ✅ High diversity and quality
🛠️ 3-Stage Data Engine
Stage | Name | Who | Method | Key Features |
---|
1️⃣ | Assisted-manual | Human + SAM | Human segments, SAM assists | Interactive tool, semantic-free |
2️⃣ | Semi-automatic | SAM + Human | SAM segments, human fills the rest | Efficient + diverse |
3️⃣ | Fully-automatic | SAM only | Grid prompts, full automation | ~100 masks/image, 99.1% of SA-1B |
Assisted-manual Stage
- Professional annotators use browser tool with SAM
- Click foreground/background points
- Refinement via brush & eraser
- Focused on recognizable objects (but no label stored)
- Moved to next image if took >30 seconds
Metric | Result |
---|
Avg. annotation time | 34 → 14 sec (6.5× faster than COCO) |
Masks/image | 20 → 44 |
Total | 120K images, 4.3M masks |
Retraining | 6 times total |
Semi-automatic Stage
Metric | Result |
---|
Additional masks | +5.9M (total 10.2M) |
Images | 180K |
Retraining | 5 more times |
Time/image | 34 sec (excluding auto-masks) |
Masks/image | 44 → 72 |
Fully Automatic Stage
- Grid of 32×32 point prompts
- Predicts multiple masks per point (sub-part, part, whole)
- IoU prediction module filters reliable masks
- Stability check with probability thresholding
- Non-Max Suppression (NMS) removes duplicates
- Cropped regions help improve small object coverage
📦 Final SA-1B Dataset Summary
Aspect | Description |
---|
Image count | 11M |
Resolution | Avg. 3300×4950 px |
Licensing | Licensed from photographers |
Privacy | Faces/plates blurred |
Released images | Resized (short side 1500 px) |
Comparison | Higher-res than COCO (480×640) |
Masks | Details |
---|
Total | 1.1B masks |
Auto-generated | 99.1% |
Human-level quality | 94% of masks have IoU > 90% w/ expert |
Fair & diverse | Balanced across gender, regions |
🔬 Zero-Shot Transfer Experiments
SAM proves it’s not just a segmentation tool, but a universal model.
Evaluated on 5 tasks without fine-tuning:
Task | Outcome |
---|
1. Single-Point Mask | Outperforms RITM (auto & human eval) |
2. Edge Detection | Strong edges from prompts (even w/o training) |
3. Object Proposal | Excellent for mid/rare objects (beats ViTDet) |
4. Instance Segmentation | Better visual quality than ViTDet, even if AP is lower |
5. Text-to-Mask | Uses CLIP text embeddings for free-text segmentation |
1️⃣ Single-Point Valid Mask
- Only one foreground point → segment object
- Evaluation: mIoU + human rating (1–10)
- SAM beats RITM on 16/23 datasets (mIoU), and all datasets (oracle mode)
- Human ratings: 7–9 (higher than RITM)
2️⃣ Edge Detection
- Dataset: BSDS500
- Prompted via 16×16 grid
- Sobel edge detection applied to mask probabilities
- Matches early DL models like HED
- Recall↑, Precision↓ due to over-segmentation (expected)
3️⃣ Object Proposal (LVIS)
- Method: Mask output used as object proposals
- Compared to ViTDet-H + Mask R-CNN
- SAM outperforms in:
- Medium/large objects
- Common/rare categories
- Falls behind on small/frequent ones
4️⃣ Instance Segmentation
- ViTDet boxes → fed as prompt to SAM
- COCO/LVIS: SAM slightly behind in AP, but
- Visual quality better (confirmed via human study)
- Less biased by noisy ground truth (unlike ViTDet)
5️⃣ Text-to-Mask
- Uses CLIP text encoder as prompt
- Training with CLIP image embedding → inference with text embedding
- Example prompts: “a wheel”, “wipers”
- Additional point improves ambiguous cases
✨ Final Thoughts
Meta didn’t just build a model — they released the model + high-quality data with strong fairness,
making a true contribution to the open AI community.
Let’s hope we can do the same in the future — building & sharing great models and datasets!
(한국어) 🧠 SAM이란 무엇인가?
『Segment Anything』(ICCV, 2023) 공부
📖 논문 제목: Segment Anything
✍️ 저자: Meta AI Research (Kirillov, Alexey et al.)
🌟 한줄 요약: 어떤 객체든, 어떤 이미지든, 어떤 입력이든 “무엇이든” 잘라내는 범용 세그멘테이션 모델의 등장!!
📚 핵심 아이디어
- SAM은 Segment Anything Model의 약자로,
- 기존의 영역 분할(Segmentation) 모델들과는 달리,
- 어떤 객체든 사전 학습된 모델 하나로 잘라낼 수 있는 범용 Segmentation 인공지능입니다!
- 즉, 미리 정의된 클래스가 없어도, “사용자 입력(Prompt)”만으로 원하는 대상을 분리할 수 있어요.
- SAM은 “Segmentation을 위한 GPT”라고 불릴 정도로 범용성이 강력합니다.
🔍 SAM 연구의 배경
- 바야흐로 Foundation Model의 시대!!
- 대량의 데이터로 Language Model들은 놀랍게 잘 작동!!
- Computer Vision 에서도 CLIP, ALIGN 등 이미지 인코더들이 등장, 이미지 생성에도 영향을 미침!!
- 하지만, Vision 데이터의 부족으로 인해 한계가 있었음!!
- 그래서!! 이번 연구의 목표는 “build a foundation model for image segmentation” 으로 정의!!
- 그리고 성공적 연구를 위해서 아래 3가지 요소를 고민함!!
a. 과제 : 어떤 과제를 설정할것인가!
b. 모델 : 어떤 모델을 쓸것인가!
c. 데이터 : 어떤 데이터를 쓸것인가!
SAM 연구의 과제(Task)의 정의
- 기존 Segmentation 모델의 한계
- 대부분의 segmentation 모델은 사전 정의된 클래스(class)가 있어야 학습 가능
- 특정 객체(ex: 고양이, 개, 자동차)만 분할 가능하며, 라벨링 데이터에 매우 의존
- 새로운 클래스에 대해선 재학습(fine-tuning)이 필요
- Open-Vocabulary, Prompt 기반 모델 필요성
- 최근 CLIP 등 멀티모달 모델의 등장과 함께,
- “텍스트”나 “포인트” 등을 통해 사용자 중심으로 객체를 지정하고 분할하는 모델이 요구됨
- 그래서!! “무엇이든 잘라내는 범용 분할기”를 과제로 정의!
⚙️ SAM의 모델 구조
구성 요소 | 설명 |
---|
Image Encoder | 이미지 전체를 인코딩하여 고정된 image embedding 생성 (한 번만 수행) |
Prompt Encoder | 점, 박스, 마스크 등 다양한 프롬프트를 인코딩 |
Mask Decoder | 이미지와 프롬프트 인코딩을 결합하여 마스크 예측 수행 |
SAM은 세 가지 주요 구성 요소 및 그 기능!!
- Image Encoder (ViT-H 기반)
- MAE (Masked Autoencoders) 방식의 ViT를 사용! - MAE가 뭔지 공부해보자!!
| Masked Autoencoders Are Scalable Vision Learners (CVPR, 2022) - 이미지를 고해상도로 인코딩하여 풍부한 시각 표현 생성
- 한번 인코딩된 이미지는 여러 프롬프트에도 재사용 가능
- Prompt Encoder
- 사용자의 입력을 인코딩
- 입력 종류 - 크게 2가지!
종류 | 예시 | 인코딩 방식 | 설명 |
---|
희소 (Sparse) | Point, Box, Text | 위치 + 학습된 임베딩 / 텍스트 인코더(CLIP) | - 위치 정보에 Positional Encoding + 학습된 임베딩 - 텍스트는 CLIP 텍스트 인코더 사용 |
밀집 (Dense) | Mask | Convolution + Element-wise Sum | - 마스크를 Conv로 임베딩 후 이미지 임베딩과 원소 단위 합산 |
Mask Decoder
- 인코더 출력을 기반으로 최종 마스크를 생성
- 이미지와 프롬프트 정보를 결합하여 마스크를 생성하는 핵심 구성
- 🔧 주요 구성 요소 및 처리 과정
단계 | 설명 |
---|
1. 입력 | - Image Embedding - Prompt Embedding (Point, Box, Text 등) - Output Token |
2. 디코더 블록 (×2) | - Transformer Decoder 변형 버전 사용 - Prompt Self-Attention - Cross-Attention (Prompt ↔ Image 임베딩) 양방향 수행 |
3. 업샘플링 | - 디코더 출력에서 Image Embedding을 업샘플링 |
4. 동적 마스크 예측 | - Output Token → MLP → 동적 Linear Classifier - 각 픽셀 위치마다 Foreground 확률 계산 |
5. 최종 출력 | - 전경 확률(foreground probability) 맵 → Binary Mask 출력 |
-모호성의 해결을 위하여! : 세 개의 후보 마스크를 출력, 각 마스크 별 확신도(uncertainty score) 제공
🏗️ SAM의 데이터 (SA-1B) 및 데이터 엔진
- SA-1B: SAM 학습을 위해 Meta가 만든 초대규모 세그멘테이션 데이터셋
- 총 11M개의 이미지에서 자동으로 수집된 1B+ 마스크
- 기존 세그멘테이션 데이터셋보다 400배 더 많은 마스크 보유
- ✅ 완전 자동 수집, ✅ 고품질 & 다양성 보장
- SAM의 범용성 및 견고성 확보에 핵심 역할
- 📚 향후 파운데이션 모델 연구를 위한 공공 자원으로 활용 가능
- SA-1B 데이터셋 생성 절차 요약 표
단계 | 명칭 | 주체 | 주요 작업 | 특징 |
---|
1️⃣ | 보조 수동 주석 (Assisted-manual) | 사람 + SAM | 사람이 마스크를 직접 만들고, SAM이 보조 | 인터랙티브 세그멘테이션 방식, 초기 품질 확보 |
2️⃣ | 반자동 주석 (Semi-automatic) | SAM + 사람 | SAM이 일부 객체 마스크 생성, 사람은 나머지를 주석 | 다양성 향상, 시간 효율 증가 |
3️⃣ | 완전 자동 주석 (Fully automatic) | SAM | SAM이 포인트 프롬프트 기반으로 전체 마스크 생성 | 이미지당 평균 100개 마스크, SA-1B 대부분 구성 |
1단계: Assisted-Manual Stage
- 브라우저 기반 인터랙티브 툴에서 SAM이 실시간으로 주석 지원
- 전문 주석자가 전경/배경 포인트 클릭하여 마스크 생성
- 브러시 & 지우개로 정밀 수정 가능
- “설명 가능한” 객체 중심으로 자유롭게 라벨링 (semantic 제한 없음)
- 마스크에 이름/설명은 저장하지 않음
- 30초 이상 걸리면 다음 이미지로 넘어감
- 수집된 마스크로 6회 재학습!!
🔁 모델 향상 과정
항목 | 내용 |
---|
초기 모델 | 공개 세그멘테이션 데이터로 학습된 SAM |
반복 학습 | 수집된 마스크만으로 총 6회 재학습 |
ViT 백본 | ViT-B → ViT-H로 점진적 확장 |
구조 개선 | 다양한 세부 구조 진화 포함 |
📈 성능 개선 지표
지표 | 변화 |
---|
평균 주석 시간 | 34초 → 14초 (COCO보다 6.5배 빠름) |
평균 마스크 수 | 이미지당 20개 → 44개 |
수집량 | 12만 이미지, 430만 마스크 수집 완료 |
2단계: Semi-Automatic Stage
- 이 단계는 “자동 + 수동 협업 구조”로, 더 어려운 객체, 더 다양한 객체를 커버하는 데 중요한 역할수행
- 마스크 다양성 향상을 통해 SAM의 범용 분할 능력 강화
- 1단계 마스크를 기반으로 “object” 클래스 하나로 바운딩 박스 탐지기 학습
- 자동 탐지된 마스크(confident masks)를 이미지에 미리 삽입
- 주석자는 자동 마스크 외의 누락된 객체만 수동으로 추가 주석
📈 성능 및 수치
항목 | 내용 |
---|
수집 마스크 수 | 590만 개 추가 수집 (총 1,020만 개 도달) |
이미지 수 | 18만 장 |
SAM 재학습 횟수 | 5회 반복 학습 |
평균 주석 시간 | 34초 (자동 마스크 제외) |
이미지당 평균 마스크 수 | 44개 → 72개 (자동 + 수동 포함) |
3단계: Fully Automatic Stage
- 2단계까지 데이터로 학습된 모델로, 완전 자동으로!!, 데이터셋 생성!!
- 이로써 Segment Anything의 SA-1B 데이터셋이 완성
- SAM 모델도 중요하지만, 이처럼 범용 분할 모델 학습에 있어 전례 없는 리소스 제공했다는점도 큰 의미!!
🔧 자동 생성 절차
- 32×32 포인트 그리드로 이미지 프롬프트
- 각 포인트에 대해 다중 마스크 예측
- 예: “팔” 포인트 → 팔 / 팔+몸통 / 전체 사람 마스크
- IoU 예측 모듈로 신뢰도 높은 마스크만 선택
- 안정성 검사:
- 확률맵을 0.5, 0.55 등으로 threshold해도 비슷하면 “안정된 마스크”
- NMS (Non-Max Suppression)로 중복 제거
- 작은 객체 보완을 위해 확대된 이미지 crop도 병렬 처리
최종 생성된 데이터(SA-1B)는!?
🖼️ 이미지 구성
항목 | 내용 |
---|
이미지 수 | 11,000,000장 |
해상도 | 평균 3300 × 4950 픽셀 |
출처 | 사진작가와 직접 협업하는 공급업체로부터 라이선스 획득 |
보호 조치 | 얼굴 및 차량 번호판 블러 처리 포함 |
배포 형식 | 최단 변 기준 1500픽셀 다운샘플 버전 제공 |
비교 | COCO: 480×640 → SA-1B는 훨씬 더 고해상도 |
🧩 마스크 구성
항목 | 내용 |
---|
총 마스크 수 | 1.1B (11억 개) |
생성 방식 | 99.1% 자동 생성 (Fully Automatic Stage) |
포함 마스크 | 최종적으로는 자동 생성된 마스크만 포함됨 |
품질 평가 | 전문가 보정 대비 94%가 IoU > 90% 수준의 일치율 |
🔍 품질 검증: 자동 vs 전문가의 검증!!
- 무작위 500개 이미지(총 5만 마스크)를 샘플링하여
전문가가 브러시 & 지우개로 마스크를 정교하게 보정 - 그 결과:
- 94%의 마스크 쌍이 IoU > 90%
- 97%는 IoU > 75%
- 참고: 기존 논문 기준 사람 간 IoU 일치율은 85~91% 수준
- ⇒ SAM의 자동 마스크는 전문가 수준의 품질 확보
PC의 데이터!!
- 남성 여성, 유럽 아시아 아프라카 등 어떤점에서도 치우치지 않은 Fairness 데이터에요!!^^*
Zero-Shot Transfer Experiments (SAM의 범용성 실험)
SAM(Segment Anything Model)은 단순히 이미지에 마스크를 그리는 도구를 넘어!!
추가 학습 없이 다양한 비전 과제에 직접 적용 가능한 범용 모델이라는 점을 실험을 통해 입증
총 5가지 실험을 통해 SAM의 Zero-Shot 성능을 측정
🧭 Zero-shot 실험 개요
- Zero-Shot Transfer: SAM은 학습에 사용되지 않은 데이터셋과 작업에 대해 직접 적용
- 평가 대상 과제 5종:
- Single-Point Valid Mask (단일 포인트 객체 분할)
- Edge Detection (에지 감지)
- Object Proposal Generation (객체 제안)
- Instance Segmentation (인스턴스 분할)
- Text-to-Mask (텍스트 → 마스크)
- 실험 요약!
실험 | 결과 요약 |
---|
Single-Point Mask | RITM 대비 정성·정량 성능 모두 우수 |
Edge Detection | 학습 없이도 의미 있는 에지 추출 가능 |
Object Proposal | 중간/희귀 객체 제안에서 최고 수준 성능 |
Instance Segmentation | AP는 낮지만 시각적 품질과 사용자 평가 우수 |
Text-to-Mask | CLIP 임베딩 활용해 자연어 분할까지 확장 성공 |
1️⃣ 단일 포인트 객체 분할 (Single-Point Valid Mask)
- 설정: 전경 포인트 하나만으로 객체 분할
- 평가: mIoU + 사람 주석자 평가 (1~10점)
- 결과:
- 23개 중 16개 데이터셋에서 RITM 대비 mIoU 우위
- Oracle 선택 시 전 데이터셋에서 RITM 능가
- 사람 평가는 7~9점으로 RITM보다 일관되게 높음
- SAM은 모호한 입력에서도 유효한 마스크 생성 능력 입증
2️⃣ 엣지 감지 (Zero-Shot Edge Detection)
- 설정: BSDS500에서 에지 감지 수행
- 16×16 포인트로 SAM을 프롬프트 → Sobel 필터로 경계 추출
- 결과:
- 에지 감지용 학습 없이도 의미 있는 에지 맵 생성
- 최신 기법보단 정밀도는 낮지만, HED 등 초기 딥러닝 모델 수준 이상
- Zero-shot 치고 매우 우수한 성능
3️⃣ 객체 제안 (Zero-Shot Object Proposal)
- 설정: LVIS에서 제안된 마스크들로 객체 제안
- 비교: ViTDet-H + Mask R-CNN (DMP 방법)
- 평가 지표: Average Recall (AR@1000)
- 결과:
- 중간/큰 객체, 희귀/일반 객체에서 ViTDet-H보다 우수
- 작은 객체에서는 ViTDet-H가 우세 (LVIS에 특화된 학습 때문)
- Ambiguity-aware 버전이 압도적 성능 향상 제공
4️⃣ 인스턴스 세분화 (Zero-Shot Instance Segmentation)
- 설정: 감지기(ViTDet) 박스를 프롬프트로 SAM에 마스크 생성
- 결과:
- COCO/LVIS에서 AP는 ViTDet보다 낮지만
- 경계 품질은 SAM이 더 우수
- 사람 평가에서도 SAM 마스크가 더 높게 평가됨
- 분석:
- COCO는 품질 낮은 GT → ViTDet는 데이터 편향 학습
- SAM은 그런 편향 없이 보다 일반적인 분할 수행
5️⃣ 텍스트 → 마스크 (Zero-Shot Text-to-Mask)
- 설정: 텍스트 프롬프트만으로 객체 분할
- CLIP의 이미지 임베딩 ↔ 텍스트 임베딩 정렬을 이용해 학습
- 결과:
- “a wheel”, “beaver tooth grille” 등 자연어로 객체 분할 가능
- 텍스트만으로 잘 안될 경우, 포인트 프롬프트를 추가하면 개선됨
- 시사점:
- SAM은 멀티모달 인터페이스로 발전 가능성이 큼
✨ 마무리하며
단순히 연구만 하기도 바쁜데,, 빅테크 기업에서 연구 모델 + 데이터셋을 공개해준다는것은!
게다가 Fairness를 갖춘 좋은데이터를 제공해준다는 것은 참 고마운 일인것 같습니다!
언젠간! 우리도 높은 품질의 데이터셋과 고성능의 모델을 공개하는 날이 오기를!@!!