SKILL.md
SKILL.mdBrowse 3 files
3,398 tokens
13,358 bytes
Token encoding: o200k_base
Snapshot 24fd22b
1---2name: segment-anything-model3description: "SAM: zero-shot image segmentation via points, boxes, masks."4version: 1.0.05author: Orchestra Research6license: MIT7dependencies: [segment-anything, transformers>=4.30.0, torch>=1.7.0]8platforms: [linux, macos, windows]9metadata:10 hermes:11 tags: [Multimodal, Image Segmentation, Computer Vision, SAM, Zero-Shot]12 13---14 15# Segment Anything Model (SAM)16 17Guide to using Meta AI's Segment Anything Model for zero-shot image segmentation.18 19## When to use SAM20 21**Use SAM when:**22- Need to segment any object in images without task-specific training23- Building interactive annotation tools with point/box prompts24- Generating training data for other vision models25- Need zero-shot transfer to new image domains26- Building object detection/segmentation pipelines27- Processing medical, satellite, or domain-specific images28 29**Key features:**30- **Zero-shot segmentation**: Works on any image domain without fine-tuning31- **Flexible prompts**: Points, bounding boxes, or previous masks32- **Automatic segmentation**: Generate all object masks automatically33- **High quality**: Trained on 1.1 billion masks from 11 million images34- **Multiple model sizes**: ViT-B (fastest), ViT-L, ViT-H (most accurate)35- **ONNX export**: Deploy in browsers and edge devices36 37**Use alternatives instead:**38- **YOLO/Detectron2**: For real-time object detection with classes39- **Mask2Former**: For semantic/panoptic segmentation with categories40- **GroundingDINO + SAM**: For text-prompted segmentation41- **SAM 2**: For video segmentation tasks42 43## Quick start44 45### Installation46 47```bash48# From GitHub49pip install git+https://github.com/facebookresearch/segment-anything.git50 51# Optional dependencies52pip install opencv-python pycocotools matplotlib53 54# Or use HuggingFace transformers55pip install transformers56```57 58### Download checkpoints59 60```bash61# ViT-H (largest, most accurate) - 2.4GB62wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth63 64# ViT-L (medium) - 1.2GB65wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth66 67# ViT-B (smallest, fastest) - 375MB68wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth69```70 71### Basic usage with SamPredictor72 73```python74import numpy as np75from segment_anything import sam_model_registry, SamPredictor76 77# Load model78sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")79sam.to(device="cuda")80 81# Create predictor82predictor = SamPredictor(sam)83 84# Set image (computes embeddings once)85image = cv2.imread("image.jpg")86image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)87predictor.set_image(image)88 89# Predict with point prompts90input_point = np.array([[500, 375]]) # (x, y) coordinates91input_label = np.array([1]) # 1 = foreground, 0 = background92 93masks, scores, logits = predictor.predict(94 point_coords=input_point,95 point_labels=input_label,96 multimask_output=True # Returns 3 mask options97)98 99# Select best mask100best_mask = masks[np.argmax(scores)]101```102 103### HuggingFace Transformers104 105```python106import torch107from PIL import Image108from transformers import SamModel, SamProcessor109 110# Load model and processor111model = SamModel.from_pretrained("facebook/sam-vit-huge")112processor = SamProcessor.from_pretrained("facebook/sam-vit-huge")113model.to("cuda")114 115# Process image with point prompt116image = Image.open("image.jpg")117input_points = [[[450, 600]]] # Batch of points118 119inputs = processor(image, input_points=input_points, return_tensors="pt")120inputs = {k: v.to("cuda") for k, v in inputs.items()}121 122# Generate masks123with torch.no_grad():124 outputs = model(**inputs)125 126# Post-process masks to original size127masks = processor.image_processor.post_process_masks(128 outputs.pred_masks.cpu(),129 inputs["original_sizes"].cpu(),130 inputs["reshaped_input_sizes"].cpu()131)132```133 134## Core concepts135 136### Model architecture137 138<!-- ascii-guard-ignore -->139```140SAM Architecture:141┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐142│ Image Encoder │────▶│ Prompt Encoder │────▶│ Mask Decoder │143│ (ViT) │ │ (Points/Boxes) │ │ (Transformer) │144└─────────────────┘ └─────────────────┘ └─────────────────┘145 │ │ │146 Image Embeddings Prompt Embeddings Masks + IoU147 (computed once) (per prompt) predictions148```149<!-- ascii-guard-ignore-end -->150 151### Model variants152 153| Model | Checkpoint | Size | Speed | Accuracy |154|-------|------------|------|-------|----------|155| ViT-H | `vit_h` | 2.4 GB | Slowest | Best |156| ViT-L | `vit_l` | 1.2 GB | Medium | Good |157| ViT-B | `vit_b` | 375 MB | Fastest | Good |158 159### Prompt types160 161| Prompt | Description | Use Case |162|--------|-------------|----------|163| Point (foreground) | Click on object | Single object selection |164| Point (background) | Click outside object | Exclude regions |165| Bounding box | Rectangle around object | Larger objects |166| Previous mask | Low-res mask input | Iterative refinement |167 168## Interactive segmentation169 170### Point prompts171 172```python173# Single foreground point174input_point = np.array([[500, 375]])175input_label = np.array([1])176 177masks, scores, logits = predictor.predict(178 point_coords=input_point,179 point_labels=input_label,180 multimask_output=True181)182 183# Multiple points (foreground + background)184input_points = np.array([[500, 375], [600, 400], [450, 300]])185input_labels = np.array([1, 1, 0]) # 2 foreground, 1 background186 187masks, scores, logits = predictor.predict(188 point_coords=input_points,189 point_labels=input_labels,190 multimask_output=False # Single mask when prompts are clear191)192```193 194### Box prompts195 196```python197# Bounding box [x1, y1, x2, y2]198input_box = np.array([425, 600, 700, 875])199 200masks, scores, logits = predictor.predict(201 box=input_box,202 multimask_output=False203)204```205 206### Combined prompts207 208```python209# Box + points for precise control210masks, scores, logits = predictor.predict(211 point_coords=np.array([[500, 375]]),212 point_labels=np.array([1]),213 box=np.array([400, 300, 700, 600]),214 multimask_output=False215)216```217 218### Iterative refinement219 220```python221# Initial prediction222masks, scores, logits = predictor.predict(223 point_coords=np.array([[500, 375]]),224 point_labels=np.array([1]),225 multimask_output=True226)227 228# Refine with additional point using previous mask229masks, scores, logits = predictor.predict(230 point_coords=np.array([[500, 375], [550, 400]]),231 point_labels=np.array([1, 0]), # Add background point232 mask_input=logits[np.argmax(scores)][None, :, :], # Use best mask233 multimask_output=False234)235```236 237## Automatic mask generation238 239### Basic automatic segmentation240 241```python242from segment_anything import SamAutomaticMaskGenerator243 244# Create generator245mask_generator = SamAutomaticMaskGenerator(sam)246 247# Generate all masks248masks = mask_generator.generate(image)249 250# Each mask contains:251# - segmentation: binary mask252# - bbox: [x, y, w, h]253# - area: pixel count254# - predicted_iou: quality score255# - stability_score: robustness score256# - point_coords: generating point257```258 259### Customized generation260 261```python262mask_generator = SamAutomaticMaskGenerator(263 model=sam,264 points_per_side=32, # Grid density (more = more masks)265 pred_iou_thresh=0.88, # Quality threshold266 stability_score_thresh=0.95, # Stability threshold267 crop_n_layers=1, # Multi-scale crops268 crop_n_points_downscale_factor=2,269 min_mask_region_area=100, # Remove tiny masks270)271 272masks = mask_generator.generate(image)273```274 275### Filtering masks276 277```python278# Sort by area (largest first)279masks = sorted(masks, key=lambda x: x['area'], reverse=True)280 281# Filter by predicted IoU282high_quality = [m for m in masks if m['predicted_iou'] > 0.9]283 284# Filter by stability score285stable_masks = [m for m in masks if m['stability_score'] > 0.95]286```287 288## Batched inference289 290### Multiple images291 292```python293# Process multiple images efficiently294images = [cv2.imread(f"image_{i}.jpg") for i in range(10)]295 296all_masks = []297for image in images:298 predictor.set_image(image)299 masks, _, _ = predictor.predict(300 point_coords=np.array([[500, 375]]),301 point_labels=np.array([1]),302 multimask_output=True303 )304 all_masks.append(masks)305```306 307### Multiple prompts per image308 309```python310# Process multiple prompts efficiently (one image encoding)311predictor.set_image(image)312 313# Batch of point prompts314points = [315 np.array([[100, 100]]),316 np.array([[200, 200]]),317 np.array([[300, 300]])318]319 320all_masks = []321for point in points:322 masks, scores, _ = predictor.predict(323 point_coords=point,324 point_labels=np.array([1]),325 multimask_output=True326 )327 all_masks.append(masks[np.argmax(scores)])328```329 330## ONNX deployment331 332### Export model333 334```bash335python scripts/export_onnx_model.py \336 --checkpoint sam_vit_h_4b8939.pth \337 --model-type vit_h \338 --output sam_onnx.onnx \339 --return-single-mask340```341 342### Use ONNX model343 344```python345import onnxruntime346 347# Load ONNX model348ort_session = onnxruntime.InferenceSession("sam_onnx.onnx")349 350# Run inference (image embeddings computed separately)351masks = ort_session.run(352 None,353 {354 "image_embeddings": image_embeddings,355 "point_coords": point_coords,356 "point_labels": point_labels,357 "mask_input": np.zeros((1, 1, 256, 256), dtype=np.float32),358 "has_mask_input": np.array([0], dtype=np.float32),359 "orig_im_size": np.array([h, w], dtype=np.float32)360 }361)362```363 364## Common workflows365 366### Workflow 1: Annotation tool367 368```python369import cv2370 371# Load model372predictor = SamPredictor(sam)373predictor.set_image(image)374 375def on_click(event, x, y, flags, param):376 if event == cv2.EVENT_LBUTTONDOWN:377 # Foreground point378 masks, scores, _ = predictor.predict(379 point_coords=np.array([[x, y]]),380 point_labels=np.array([1]),381 multimask_output=True382 )383 # Display best mask384 display_mask(masks[np.argmax(scores)])385```386 387### Workflow 2: Object extraction388 389```python390def extract_object(image, point):391 """Extract object at point with transparent background."""392 predictor.set_image(image)393 394 masks, scores, _ = predictor.predict(395 point_coords=np.array([point]),396 point_labels=np.array([1]),397 multimask_output=True398 )399 400 best_mask = masks[np.argmax(scores)]401 402 # Create RGBA output403 rgba = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)404 rgba[:, :, :3] = image405 rgba[:, :, 3] = best_mask * 255406 407 return rgba408```409 410### Workflow 3: Medical image segmentation411 412```python413# Process medical images (grayscale to RGB)414medical_image = cv2.imread("scan.png", cv2.IMREAD_GRAYSCALE)415rgb_image = cv2.cvtColor(medical_image, cv2.COLOR_GRAY2RGB)416 417predictor.set_image(rgb_image)418 419# Segment region of interest420masks, scores, _ = predictor.predict(421 box=np.array([x1, y1, x2, y2]), # ROI bounding box422 multimask_output=True423)424```425 426## Output format427 428### Mask data structure429 430```python431# SamAutomaticMaskGenerator output432{433 "segmentation": np.ndarray, # H×W binary mask434 "bbox": [x, y, w, h], # Bounding box435 "area": int, # Pixel count436 "predicted_iou": float, # 0-1 quality score437 "stability_score": float, # 0-1 robustness score438 "crop_box": [x, y, w, h], # Generation crop region439 "point_coords": [[x, y]], # Input point440}441```442 443### COCO RLE format444 445```python446from pycocotools import mask as mask_utils447 448# Encode mask to RLE449rle = mask_utils.encode(np.asfortranarray(mask.astype(np.uint8)))450rle["counts"] = rle["counts"].decode("utf-8")451 452# Decode RLE to mask453decoded_mask = mask_utils.decode(rle)454```455 456## Performance optimization457 458### GPU memory459 460```python461# Use smaller model for limited VRAM462sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")463 464# Process images in batches465# Clear CUDA cache between large batches466torch.cuda.empty_cache()467```468 469### Speed optimization470 471```python472# Use half precision473sam = sam.half()474 475# Reduce points for automatic generation476mask_generator = SamAutomaticMaskGenerator(477 model=sam,478 points_per_side=16, # Default is 32479)480 481# Use ONNX for deployment482# Export with --return-single-mask for faster inference483```484 485## Common issues486 487| Issue | Solution |488|-------|----------|489| Out of memory | Use ViT-B model, reduce image size |490| Slow inference | Use ViT-B, reduce points_per_side |491| Poor mask quality | Try different prompts, use box + points |492| Edge artifacts | Use stability_score filtering |493| Small objects missed | Increase points_per_side |494 495## References496 497- **[Advanced Usage](references/advanced-usage.md)** - Batching, fine-tuning, integration498- **[Troubleshooting](references/troubleshooting.md)** - Common issues and solutions499 500## Resources501 502- **GitHub**: https://github.com/facebookresearch/segment-anything503- **Paper**: https://arxiv.org/abs/2304.02643504- **Demo**: https://segment-anything.com505- **SAM 2 (Video)**: https://github.com/facebookresearch/segment-anything-2506- **HuggingFace**: https://huggingface.co/facebook/sam-vit-huge507 Discovery context
Discovered by repository scan. No exact path reference found in the snapshot’s root AGENTS.md.