Skip to main content

SAM — Segment Anything Model

SAM(Segment Anything Model)은 Meta AI가 개발한 범용 세그멘테이션 파운데이션 모델입니다. 점, 박스, 텍스트 등 다양한 프롬프트로 어떤 이미지에서든 객체를 세그멘테이션할 수 있습니다.

핵심 아이디어

기존 세그멘테이션 모델은 특정 클래스에 대해서만 학습됩니다. SAM은 11억 개의 마스크와 1,100만 장의 이미지로 학습되어, 학습하지 않은 새로운 객체도 프롬프트만으로 세그멘테이션할 수 있습니다. 이는 NLP의 GPT처럼 프롬프트 기반 범용 모델의 비전 버전입니다.

동작 방식

구성 요소역할특징
Image Encoder이미지 특징 추출ViT-H (632M 파라미터)
Prompt Encoder프롬프트 인코딩점, 박스, 마스크, 텍스트
Mask Decoder마스크 생성경량 Transformer Decoder

구현

기본 사용법

from segment_anything import sam_model_registry, SamPredictor
import cv2

# 모델 로드
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam = sam.to('cuda')
predictor = SamPredictor(sam)

# 이미지 설정
image = cv2.imread("image.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
predictor.set_image(image)

포인트 프롬프트

import numpy as np

# 클릭 좌표로 세그멘테이션 (포그라운드 점)
input_point = np.array([[500, 375]])
input_label = np.array([1])  # 1: 포그라운드, 0: 배경

masks, scores, logits = predictor.predict(
    point_coords=input_point,
    point_labels=input_label,
    multimask_output=True,  # 3개의 마스크 후보 생성
)

# 가장 높은 점수의 마스크 선택
best_mask = masks[scores.argmax()]
print(f"마스크 형태: {best_mask.shape}")  # [H, W] boolean
print(f"최고 점수: {scores.max():.4f}")

바운딩 박스 프롬프트

# 바운딩 박스로 세그멘테이션
input_box = np.array([100, 150, 400, 450])  # [x1, y1, x2, y2]

masks, scores, logits = predictor.predict(
    box=input_box,
    multimask_output=False,
)

전체 이미지 자동 세그멘테이션

from segment_anything import SamAutomaticMaskGenerator

# 자동 마스크 생성기
mask_generator = SamAutomaticMaskGenerator(
    model=sam,
    points_per_side=32,       # 그리드 밀도
    pred_iou_thresh=0.86,     # IoU 임계값
    stability_score_thresh=0.92,
    min_mask_region_area=100,  # 최소 마스크 면적
)

masks = mask_generator.generate(image)
print(f"생성된 마스크 수: {len(masks)}")

# 마스크 정렬 (면적 순)
sorted_masks = sorted(masks, key=lambda x: x['area'], reverse=True)
for i, mask in enumerate(sorted_masks[:5]):
    print(f"마스크 {i}: 면적={mask['area']}, IoU={mask['predicted_iou']:.3f}")

SAM2: 비디오 세그멘테이션

SAM2는 SAM을 비디오로 확장한 모델입니다. 첫 프레임에서 프롬프트를 주면 이후 프레임에서 자동으로 객체를 추적하며 세그멘테이션합니다.
비교 항목SAMSAM2
입력이미지이미지 + 비디오
추적불가자동 추적
메모리프레임 독립시간적 메모리
속도느림 (ViT-H)빠름 (Hiera 백본)
import torch
from sam2.build_sam import build_sam2_video_predictor

# SAM2 비디오 예측기
predictor = build_sam2_video_predictor(
    "sam2_hiera_large.yaml",
    "sam2_hiera_large.pt",
)

# 비디오 초기화
with torch.inference_mode():
    state = predictor.init_state(video_path="video.mp4")

    # 첫 프레임에서 프롬프트 (클릭)
    _, _, masks = predictor.add_new_points_or_box(
        state, frame_idx=0,
        obj_id=1,
        points=np.array([[400, 300]]),
        labels=np.array([1]),
    )

    # 전체 비디오 전파
    for frame_idx, obj_ids, masks in predictor.propagate_in_video(state):
        print(f"프레임 {frame_idx}: {len(obj_ids)}개 객체 추적 중")

관련 기술 비교

비교 항목SAMUNet/DeepLabYOLO-Seg
학습 필요불필요 (제로샷)필요필요
클래스 레이블없음있음있음
프롬프트필요불필요불필요
범용성매우 높음도메인 특화도메인 특화
추천 용도라벨링 보조, 범용 세그멘테이션특정 태스크 학습실시간 인스턴스
네, 가장 유용한 활용 사례 중 하나입니다. SAM으로 초기 마스크를 자동 생성한 뒤, 사람이 수정하면 라벨링 시간을 크게 단축할 수 있습니다. Label Studio도 SAM 연동을 지원합니다.
아닙니다. SAM은 “어디가 객체인지”만 알려주며, “무슨 객체인지”는 판단하지 않습니다. 클래스 분류가 필요하면 SAM의 마스크에 별도의 분류 모델을 결합하거나, Grounding DINO + SAM 파이프라인을 사용하세요.

참고 논문

논문학회/연도링크
Segment Anything (SAM)ICCV 2023arXiv:2304.02643
SAM 2: Segment Anything in Images and VideosarXiv 2024arXiv:2408.00714