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.
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.
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.
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)} ํ๋ ์ ์ธ๊ทธ๋ฉํ
์ด์
์๋ฃ")
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 |
"To reduce image labeling time, let's introduce semi-automatic annotation with SAM. Just click a few points and masks are generated automatically."
"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."
"SAM automatically classifies every object." โ SAM is a segmentation model and does not perform object "classification." It only generates masks.