๐Ÿค– AI/ML

Segment Anything

SAM (Segment Anything Model)

A general-purpose image segmentation foundation model developed by Meta AI. It can segment any object with various prompts such as points, boxes, and text, and SAM 2 also supports video segmentation.

๐Ÿ“– Detailed Explanation

Segment Anything Model (SAM) is a general-purpose image segmentation foundation model released by Meta AI in 2023. Unlike earlier segmentation models, which were trained specifically for particular domains (medical imaging, autonomous driving, etc.), SAM was trained on more than 1.1 billion masks (the SA-1B dataset) and has "zero-shot" capability, allowing it to segment objects in any kind of image.

SAM's core architecture consists of three components. The Image Encoder is based on a ViT (Vision Transformer) and converts an image into a high-dimensional embedding. The Prompt Encoder processes prompts in various forms, such as points, boxes, masks, and text. The Mask Decoder combines the image embedding and the prompt embedding to generate the final segmentation mask. Thanks to this structure, once an image has been encoded, multiple objects can be segmented quickly with various prompts.

SAM 2, released in July 2024, is an extended version that supports video segmentation as well as images. It introduces a Streaming Memory Architecture to track objects while maintaining temporal continuity between video frames. SAM 2 achieved 6 times higher accuracy in image segmentation compared with the original SAM and shows an inference speed of about 44 FPS in real time. In addition, SAM 2.1 was released in September 2024, further improving performance on visually similar objects and in occlusion situations.

SAM is used in a wide variety of fields. It is used across many industries, such as segmenting tumors or organs in medical imaging, recognizing roads and vehicles in autonomous driving, and separating products from their backgrounds in e-commerce. In particular, when combined with labeling tools, it can cut data annotation time by 8.4 times, greatly improving the productivity of ML pipelines. It is released as open source under the Apache 2.0 license, so commercial use is also possible.

๐Ÿ’ป Code Example

This is an example of segmenting objects in an image using SAM. It uses a point prompt to segment the object at a specific location.

# pip install segment-anything opencv-python matplotlib torch torchvision
import numpy as np
import matplotlib.pyplot as plt
from segment_anything import sam_model_registry, SamPredictor
import cv2

# ๋ชจ๋ธ ๋กœ๋“œ (vit_h, vit_l, vit_b ์ค‘ ์„ ํƒ)
sam_checkpoint = "sam_vit_h_4b8939.pth"  # ๋‹ค์šด๋กœ๋“œ ํ•„์š”
model_type = "vit_h"

device = "cuda"  # GPU ์‚ฌ์šฉ, CPU๋Š” "cpu"
sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
sam.to(device=device)

predictor = SamPredictor(sam)

# ์ด๋ฏธ์ง€ ๋กœ๋“œ
image = cv2.imread("your_image.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# ์ด๋ฏธ์ง€ ์ž„๋ฒ ๋”ฉ ์ƒ์„ฑ (ํ•œ ๋ฒˆ๋งŒ ์‹คํ–‰)
predictor.set_image(image)

# ์  ํ”„๋กฌํ”„ํŠธ๋กœ ์„ธ๊ทธ๋ฉ˜ํ…Œ์ด์…˜
# (x, y) ์ขŒํ‘œ, label 1=์ „๊ฒฝ, 0=๋ฐฐ๊ฒฝ
input_point = np.array([[500, 375]])
input_label = np.array([1])

masks, scores, logits = predictor.predict(
    point_coords=input_point,
    point_labels=input_label,
    multimask_output=True,  # ์—ฌ๋Ÿฌ ๋งˆ์Šคํฌ ํ›„๋ณด ๋ฐ˜ํ™˜
)

# ๊ฐ€์žฅ ๋†’์€ ์ ์ˆ˜์˜ ๋งˆ์Šคํฌ ์„ ํƒ
best_mask_idx = np.argmax(scores)
best_mask = masks[best_mask_idx]

# ๊ฒฐ๊ณผ ์‹œ๊ฐํ™”
def show_mask(mask, ax, color=(30/255, 144/255, 255/255, 0.6)):
    h, w = mask.shape[-2:]
    mask_image = mask.reshape(h, w, 1) * np.array([*color[:3], color[3]])
    ax.imshow(mask_image)

fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.imshow(image)
show_mask(best_mask, ax)
ax.scatter(input_point[:, 0], input_point[:, 1], c='red', s=200, marker='*')
ax.set_title(f"Score: {scores[best_mask_idx]:.3f}")
ax.axis('off')
plt.savefig("segmentation_result.png", bbox_inches='tight')
plt.show()

print(f"๋ถ„ํ• ๋œ ๋งˆ์Šคํฌ ๊ฐœ์ˆ˜: {len(masks)}")
print(f"๊ฐ ๋งˆ์Šคํฌ ์ ์ˆ˜: {scores}")

Video Segmentation with SAM 2

# pip install sam2
import torch
from sam2.build_sam import build_sam2_video_predictor

# SAM 2 ๋น„๋””์˜ค ๋ชจ๋ธ ๋กœ๋“œ
predictor = build_sam2_video_predictor(
    "sam2_hiera_large.yaml",
    "sam2_hiera_large.pt"
)

# ๋น„๋””์˜ค ์ดˆ๊ธฐํ™”
video_path = "your_video.mp4"
inference_state = predictor.init_state(video_path=video_path)

# ์ฒซ ํ”„๋ ˆ์ž„์—์„œ ๊ฐ์ฒด ์„ ํƒ (์  ํ”„๋กฌํ”„ํŠธ)
frame_idx = 0
obj_id = 1
points = np.array([[500, 375]], dtype=np.float32)
labels = np.array([1], dtype=np.int32)

# ํ”„๋กฌํ”„ํŠธ ์ถ”๊ฐ€
_, out_obj_ids, out_mask_logits = predictor.add_new_points(
    inference_state=inference_state,
    frame_idx=frame_idx,
    obj_id=obj_id,
    points=points,
    labels=labels,
)

# ์ „์ฒด ๋น„๋””์˜ค ์ „ํŒŒ
video_segments = {}
for out_frame_idx, out_obj_ids, out_mask_logits in predictor.propagate_in_video(
    inference_state
):
    video_segments[out_frame_idx] = {
        out_obj_id: (out_mask_logits[i] > 0.0).cpu().numpy()
        for i, out_obj_id in enumerate(out_obj_ids)
    }

print(f"์ด {len(video_segments)} ํ”„๋ ˆ์ž„ ์„ธ๊ทธ๋ฉ˜ํ…Œ์ด์…˜ ์™„๋ฃŒ")

๐Ÿ“Š Performance & Cost

SAM and SAM 2 are provided free and open source. Commercial use is possible under the Apache 2.0 license.

Model Parameter Image Size Inference Speed (A100) VRAM
SAM ViT-B 91M 1024x1024 ~50 FPS ~4GB
SAM ViT-L 308M 1024x1024 ~35 FPS ~8GB
SAM ViT-H 636M 1024x1024 ~20 FPS ~16GB
SAM 2 Tiny 38.9M 1024x1024 ~47 FPS ~3GB
SAM 2 Small 46M 1024x1024 ~44 FPS ~4GB
SAM 2 Large 224.4M 1024x1024 ~30 FPS ~8GB

Performance Comparison (Benchmarks)

Metric SAM (ViT-H) SAM 2 (Large) Notes
Image Segmentation Accuracy Baseline 6x improvement Meta official benchmark
Video Segmentation J&F Not supported SOTA SA-V dataset
Annotation Speed Fast 8.4x faster Compared with manual work
Real-time Processing Possible (30+ FPS) Possible (44 FPS) On an A100

๐Ÿ—ฃ๏ธ Say It Like This in Practice

Correct Expression

"To reduce image labeling time, let's introduce semi-automatic annotation with SAM. Just click a few points and masks are generated automatically."

Correct Expression

"If you need object tracking in video, try SAM 2. Select the object in the first frame, and it is automatically propagated to the remaining frames."

Incorrect Expression

"SAM automatically classifies every object." โ†’ SAM is a segmentation model and does not perform object "classification." It only generates masks.

โš ๏ธ Common Mistakes & Cautions

  • Prompt placement matters: Point prompts should be placed at the center of the object to get an accurate mask. Near the boundary, they can produce ambiguous results.
  • Use multimask_output: In ambiguous cases it returns multiple mask candidates, so check the scores and select the best mask.
  • Image encoding caching: It is efficient to call set_image() only once and then call predict() repeatedly with multiple prompts.
  • GPU memory: The ViT-H model requires 16GB+ of VRAM. If memory is insufficient, use ViT-B or SAM 2 Tiny.
  • SAM does not classify: It only generates masks and does not tell you "what this is." If classification is needed, combine it with a separate model.
  • Long video sequences with SAM 2: In long videos, memory accumulation and drift can occur. Consider periodic re-initialization.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More