[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6QFZW3WTKD8WPNKAF9DAZG9":3,"skill-same:01M6QFZW3WTKD8WPNKAF9DAZG9":95},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":26,"publishedAt":47,"linkOnly":48,"markdownContent":49,"markdownBody":50,"frontMatter":51,"refName":58,"commitSha":59,"skillDirectory":60,"forksCount":14,"repositoryHtmlUrl":61,"repositoryHomepageUrl":62,"ownerHtmlUrl":63,"ownerBlogUrl":64,"ownerDescription":65,"updatedAt":66,"install":67,"resources":80},"01M6QFZW3WTKD8WPNKAF9DAZG9","segment-anything-model",null,"Foundation model for image segmentation with zero-shot transfer. Use when you need to segment any object in images using points, boxes, or masks as prompts, or automatically generate all object masks in an image.","Tashima-Tarsh\u002FDisha6.6","Tashima-Tarsh","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F269906498?v=4","01M6PBH98X03XERH0HFT4PFB1P","NITISH KUMAR","01M6PBH9DA0M6KM3Z12P848F0K",0,"MIT","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-segment-anything-model\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],"segment anything","model","segment","segment anything model","for","image","object","you","Zero-Shot","boxes","as","foundation","images","vision","use","computer","segmentation","Transformers","multimodal","generate","2026-11-10 10:12:30",false,"---\nname: segment-anything-model\ndescription: Foundation model for image segmentation with zero-shot transfer. Use when you need to segment any object in images using points, boxes, or masks as prompts, or automatically generate all object masks in an image.\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  category: multimodal-and-emerging\n  maintainer: Kalaris Labs\n  tags: Multimodal, Image Segmentation, Computer Vision, SAM, Zero-Shot\n  dependencies: segment-anything, transformers>=4.30.0, torch>=1.7.0\n---\n\n# Segment Anything Model (SAM)\n\nComprehensive guide to using Meta AI's Segment Anything Model for zero-shot image segmentation.\n\n## When to use SAM\n\n**Use SAM when:**\n- Need to segment any object in images without task-specific training\n- Building interactive annotation tools with point\u002Fbox prompts\n- Generating training data for other vision models\n- Need zero-shot transfer to new image domains\n- Building object detection\u002Fsegmentation pipelines\n- Processing medical, satellite, or domain-specific images\n\n**Key features:**\n- **Zero-shot segmentation**: Works on any image domain without fine-tuning\n- **Flexible prompts**: Points, bounding boxes, or previous masks\n- **Automatic segmentation**: Generate all object masks automatically\n- **High quality**: Trained on 1.1 billion masks from 11 million images\n- **Multiple model sizes**: ViT-B (fastest), ViT-L, ViT-H (most accurate)\n- **ONNX export**: Deploy in browsers and edge devices\n\n**Use alternatives instead:**\n- **YOLO\u002FDetectron2**: For real-time object detection with classes\n- **Mask2Former**: For semantic\u002Fpanoptic segmentation with categories\n- **GroundingDINO + SAM**: For text-prompted segmentation\n- **SAM 2**: For video segmentation tasks\n\n## Quick start\n\n### Installation\n\n```bash\n# From GitHub\npip install git+https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Fsegment-anything.git\n\n# Optional dependencies\npip install opencv-python pycocotools matplotlib\n\n# Or use HuggingFace transformers\npip install transformers\n```\n\n### Download checkpoints\n\n```bash\n# ViT-H (largest, most accurate) - 2.4GB\nwget https:\u002F\u002Fdl.fbaipublicfiles.com\u002Fsegment_anything\u002Fsam_vit_h_4b8939.pth\n\n# ViT-L (medium) - 1.2GB\nwget https:\u002F\u002Fdl.fbaipublicfiles.com\u002Fsegment_anything\u002Fsam_vit_l_0b3195.pth\n\n# ViT-B (smallest, fastest) - 375MB\nwget https:\u002F\u002Fdl.fbaipublicfiles.com\u002Fsegment_anything\u002Fsam_vit_b_01ec64.pth\n```\n\n### Basic usage with SamPredictor\n\n```python\nimport numpy as np\nfrom segment_anything import sam_model_registry, SamPredictor\n\n# Load model\nsam = sam_model_registry[\"vit_h\"](checkpoint=\"sam_vit_h_4b8939.pth\")\nsam.to(device=\"cuda\")\n\n# Create predictor\npredictor = SamPredictor(sam)\n\n# Set image (computes embeddings once)\nimage = cv2.imread(\"image.jpg\")\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\npredictor.set_image(image)\n\n# Predict with point prompts\ninput_point = np.array([[500, 375]])  # (x, y) coordinates\ninput_label = np.array([1])  # 1 = foreground, 0 = background\n\nmasks, scores, logits = predictor.predict(\n    point_coords=input_point,\n    point_labels=input_label,\n    multimask_output=True  # Returns 3 mask options\n)\n\n# Select best mask\nbest_mask = masks[np.argmax(scores)]\n```\n\n### HuggingFace Transformers\n\n```python\nimport torch\nfrom PIL import Image\nfrom transformers import SamModel, SamProcessor\n\n# Load model and processor\nmodel = SamModel.from_pretrained(\"facebook\u002Fsam-vit-huge\")\nprocessor = SamProcessor.from_pretrained(\"facebook\u002Fsam-vit-huge\")\nmodel.to(\"cuda\")\n\n# Process image with point prompt\nimage = Image.open(\"image.jpg\")\ninput_points = [[[450, 600]]]  # Batch of points\n\ninputs = processor(image, input_points=input_points, return_tensors=\"pt\")\ninputs = {k: v.to(\"cuda\") for k, v in inputs.items()}\n\n# Generate masks\nwith torch.no_grad():\n    outputs = model(**inputs)\n\n# Post-process masks to original size\nmasks = processor.image_processor.post_process_masks(\n    outputs.pred_masks.cpu(),\n    inputs[\"original_sizes\"].cpu(),\n    inputs[\"reshaped_input_sizes\"].cpu()\n)\n```\n\n## Core concepts\n\n### Model architecture\n\n```\nSAM Architecture:\n┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐\n│  Image Encoder  │────▶│ Prompt Encoder  │────▶│  Mask Decoder   │\n│     (ViT)       │     │ (Points\u002FBoxes)  │     │ (Transformer)   │\n└─────────────────┘     └─────────────────┘     └─────────────────┘\n        │                       │                       │\n   Image Embeddings      Prompt Embeddings         Masks + IoU\n   (computed once)       (per prompt)             predictions\n```\n\n### Model variants\n\n| Model | Checkpoint | Size | Speed | Accuracy |\n|-------|------------|------|-------|----------|\n| ViT-H | `vit_h` | 2.4 GB | Slowest | Best |\n| ViT-L | `vit_l` | 1.2 GB | Medium | Good |\n| ViT-B | `vit_b` | 375 MB | Fastest | Good |\n\n### Prompt types\n\n| Prompt | Description | Use Case |\n|--------|-------------|----------|\n| Point (foreground) | Click on object | Single object selection |\n| Point (background) | Click outside object | Exclude regions |\n| Bounding box | Rectangle around object | Larger objects |\n| Previous mask | Low-res mask input | Iterative refinement |\n\n## Interactive segmentation\n\nDetails, code examples and parameter tables: [references\u002Finteractive-segmentation.md](references\u002Finteractive-segmentation.md). Read it when this step applies.\n\n## Automatic mask generation\n\n### Basic automatic segmentation\n\n```python\nfrom segment_anything import SamAutomaticMaskGenerator\n\n# Create generator\nmask_generator = SamAutomaticMaskGenerator(sam)\n\n# Generate all masks\nmasks = mask_generator.generate(image)\n\n# Each mask contains:\n# - segmentation: binary mask\n# - bbox: [x, y, w, h]\n# - area: pixel count\n# - predicted_iou: quality score\n# - stability_score: robustness score\n# - point_coords: generating point\n```\n\n### Customized generation\n\n```python\nmask_generator = SamAutomaticMaskGenerator(\n    model=sam,\n    points_per_side=32,          # Grid density (more = more masks)\n    pred_iou_thresh=0.88,        # Quality threshold\n    stability_score_thresh=0.95,  # Stability threshold\n    crop_n_layers=1,             # Multi-scale crops\n    crop_n_points_downscale_factor=2,\n    min_mask_region_area=100,    # Remove tiny masks\n)\n\nmasks = mask_generator.generate(image)\n```\n\n### Filtering masks\n\n```python\n# Sort by area (largest first)\nmasks = sorted(masks, key=lambda x: x['area'], reverse=True)\n\n# Filter by predicted IoU\nhigh_quality = [m for m in masks if m['predicted_iou'] > 0.9]\n\n# Filter by stability score\nstable_masks = [m for m in masks if m['stability_score'] > 0.95]\n```\n\n## Batched inference\n\n### Multiple images\n\n```python\n# Process multiple images efficiently\nimages = [cv2.imread(f\"image_{i}.jpg\") for i in range(10)]\n\nall_masks = []\nfor image in images:\n    predictor.set_image(image)\n    masks, _, _ = predictor.predict(\n        point_coords=np.array([[500, 375]]),\n        point_labels=np.array([1]),\n        multimask_output=True\n    )\n    all_masks.append(masks)\n```\n\n### Multiple prompts per image\n\n```python\n# Process multiple prompts efficiently (one image encoding)\npredictor.set_image(image)\n\n# Batch of point prompts\npoints = [\n    np.array([[100, 100]]),\n    np.array([[200, 200]]),\n    np.array([[300, 300]])\n]\n\nall_masks = []\nfor point in points:\n    masks, scores, _ = predictor.predict(\n        point_coords=point,\n        point_labels=np.array([1]),\n        multimask_output=True\n    )\n    all_masks.append(masks[np.argmax(scores)])\n```\n\n## ONNX deployment\n\n### Export model\n\n```bash\npython scripts\u002Fexport_onnx_model.py \\\n    --checkpoint sam_vit_h_4b8939.pth \\\n    --model-type vit_h \\\n    --output sam_onnx.onnx \\\n    --return-single-mask\n```\n\n### Use ONNX model\n\n```python\nimport onnxruntime\n\n# Load ONNX model\nort_session = onnxruntime.InferenceSession(\"sam_onnx.onnx\")\n\n# Run inference (image embeddings computed separately)\nmasks = ort_session.run(\n    None,\n    {\n        \"image_embeddings\": image_embeddings,\n        \"point_coords\": point_coords,\n        \"point_labels\": point_labels,\n        \"mask_input\": np.zeros((1, 1, 256, 256), dtype=np.float32),\n        \"has_mask_input\": np.array([0], dtype=np.float32),\n        \"orig_im_size\": np.array([h, w], dtype=np.float32)\n    }\n)\n```\n\n## Common workflows\n\n### Workflow 1: Annotation tool\n\n```python\nimport cv2\n\n# Load model\npredictor = SamPredictor(sam)\npredictor.set_image(image)\n\ndef on_click(event, x, y, flags, param):\n    if event == cv2.EVENT_LBUTTONDOWN:\n        # Foreground point\n        masks, scores, _ = predictor.predict(\n            point_coords=np.array([[x, y]]),\n            point_labels=np.array([1]),\n            multimask_output=True\n        )\n        # Display best mask\n        display_mask(masks[np.argmax(scores)])\n```\n\n### Workflow 2: Object extraction\n\n```python\ndef extract_object(image, point):\n    \"\"\"Extract object at point with transparent background.\"\"\"\n    predictor.set_image(image)\n\n    masks, scores, _ = predictor.predict(\n        point_coords=np.array([point]),\n        point_labels=np.array([1]),\n        multimask_output=True\n    )\n\n    best_mask = masks[np.argmax(scores)]\n\n    # Create RGBA output\n    rgba = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)\n    rgba[:, :, :3] = image\n    rgba[:, :, 3] = best_mask * 255\n\n    return rgba\n```\n\n### Workflow 3: Medical image segmentation\n\n```python\n# Process medical images (grayscale to RGB)\nmedical_image = cv2.imread(\"scan.png\", cv2.IMREAD_GRAYSCALE)\nrgb_image = cv2.cvtColor(medical_image, cv2.COLOR_GRAY2RGB)\n\npredictor.set_image(rgb_image)\n\n# Segment region of interest\nmasks, scores, _ = predictor.predict(\n    box=np.array([x1, y1, x2, y2]),  # ROI bounding box\n    multimask_output=True\n)\n```\n\n## Output format\n\n### Mask data structure\n\n```python\n# SamAutomaticMaskGenerator output\n{\n    \"segmentation\": np.ndarray,  # H×W binary mask\n    \"bbox\": [x, y, w, h],        # Bounding box\n    \"area\": int,                 # Pixel count\n    \"predicted_iou\": float,      # 0-1 quality score\n    \"stability_score\": float,    # 0-1 robustness score\n    \"crop_box\": [x, y, w, h],    # Generation crop region\n    \"point_coords\": [[x, y]],    # Input point\n}\n```\n\n### COCO RLE format\n\n```python\nfrom pycocotools import mask as mask_utils\n\n# Encode mask to RLE\nrle = mask_utils.encode(np.asfortranarray(mask.astype(np.uint8)))\nrle[\"counts\"] = rle[\"counts\"].decode(\"utf-8\")\n\n# Decode RLE to mask\ndecoded_mask = mask_utils.decode(rle)\n```\n\n## Performance optimization\n\n### GPU memory\n\n```python\n# Use smaller model for limited VRAM\nsam = sam_model_registry[\"vit_b\"](checkpoint=\"sam_vit_b_01ec64.pth\")\n\n# Process images in batches\n# Clear CUDA cache between large batches\ntorch.cuda.empty_cache()\n```\n\n### Speed optimization\n\n```python\n# Use half precision\nsam = sam.half()\n\n# Reduce points for automatic generation\nmask_generator = SamAutomaticMaskGenerator(\n    model=sam,\n    points_per_side=16,  # Default is 32\n)\n\n# Use ONNX for deployment\n# Export with --return-single-mask for faster inference\n```\n\n## Common issues\n\n| Issue | Solution |\n|-------|----------|\n| Out of memory | Use ViT-B model, reduce image size |\n| Slow inference | Use ViT-B, reduce points_per_side |\n| Poor mask quality | Try different prompts, use box + points |\n| Edge artifacts | Use stability_score filtering |\n| Small objects missed | Increase points_per_side |\n\n## References\n\n- **[Advanced Usage](references\u002Fadvanced-usage.md)** - Batching, fine-tuning, integration\n- **[Troubleshooting](references\u002Ftroubleshooting.md)** - Common issues and solutions\n\n## Resources\n\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Fsegment-anything\n- **Paper**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2304.02643\n- **Demo**: https:\u002F\u002Fsegment-anything.com\n- **SAM 2 (Video)**: https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Fsegment-anything-2\n- **HuggingFace**: https:\u002F\u002Fhuggingface.co\u002Ffacebook\u002Fsam-vit-huge\n\n## Agent operating procedure\n\n1. **Check the environment.** Confirm GPU memory, model checkpoint and licence, framework versions and input formats.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Run inference on a single sample at low resolution or short length first.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Inspect outputs qualitatively and with task metrics; check licence restrictions for generated content.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Out-of-memory on large inputs | Reduce resolution or sequence length, use half precision, or tile the input. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Check model and dataset licences before commercial or published use.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n\n## Related skills\n\n- `clip`: OpenAI's model connecting vision and language.\n- `generate-image`: Generate or edit images with AI models through the OpenRouter Image API (Gemini, Seedream, Recraft, GPT-Image, Riverflow).\n- `blip-2-vision-language`: Explains how to use Salesforce BLIP-2 (Q-Former bridging a frozen image encoder and an LLM such as OPT or FlanT5) through HuggingFace Trans…\n","# Segment Anything Model (SAM)\n\nComprehensive guide to using Meta AI's Segment Anything Model for zero-shot image segmentation.\n\n## When to use SAM\n\n**Use SAM when:**\n- Need to segment any object in images without task-specific training\n- Building interactive annotation tools with point\u002Fbox prompts\n- Generating training data for other vision models\n- Need zero-shot transfer to new image domains\n- Building object detection\u002Fsegmentation pipelines\n- Processing medical, satellite, or domain-specific images\n\n**Key features:**\n- **Zero-shot segmentation**: Works on any image domain without fine-tuning\n- **Flexible prompts**: Points, bounding boxes, or previous masks\n- **Automatic segmentation**: Generate all object masks automatically\n- **High quality**: Trained on 1.1 billion masks from 11 million images\n- **Multiple model sizes**: ViT-B (fastest), ViT-L, ViT-H (most accurate)\n- **ONNX export**: Deploy in browsers and edge devices\n\n**Use alternatives instead:**\n- **YOLO\u002FDetectron2**: For real-time object detection with classes\n- **Mask2Former**: For semantic\u002Fpanoptic segmentation with categories\n- **GroundingDINO + SAM**: For text-prompted segmentation\n- **SAM 2**: For video segmentation tasks\n\n## Quick start\n\n### Installation\n\n```bash\n# From GitHub\npip install git+https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Fsegment-anything.git\n\n# Optional dependencies\npip install opencv-python pycocotools matplotlib\n\n# Or use HuggingFace transformers\npip install transformers\n```\n\n### Download checkpoints\n\n```bash\n# ViT-H (largest, most accurate) - 2.4GB\nwget https:\u002F\u002Fdl.fbaipublicfiles.com\u002Fsegment_anything\u002Fsam_vit_h_4b8939.pth\n\n# ViT-L (medium) - 1.2GB\nwget https:\u002F\u002Fdl.fbaipublicfiles.com\u002Fsegment_anything\u002Fsam_vit_l_0b3195.pth\n\n# ViT-B (smallest, fastest) - 375MB\nwget https:\u002F\u002Fdl.fbaipublicfiles.com\u002Fsegment_anything\u002Fsam_vit_b_01ec64.pth\n```\n\n### Basic usage with SamPredictor\n\n```python\nimport numpy as np\nfrom segment_anything import sam_model_registry, SamPredictor\n\n# Load model\nsam = sam_model_registry[\"vit_h\"](checkpoint=\"sam_vit_h_4b8939.pth\")\nsam.to(device=\"cuda\")\n\n# Create predictor\npredictor = SamPredictor(sam)\n\n# Set image (computes embeddings once)\nimage = cv2.imread(\"image.jpg\")\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\npredictor.set_image(image)\n\n# Predict with point prompts\ninput_point = np.array([[500, 375]])  # (x, y) coordinates\ninput_label = np.array([1])  # 1 = foreground, 0 = background\n\nmasks, scores, logits = predictor.predict(\n    point_coords=input_point,\n    point_labels=input_label,\n    multimask_output=True  # Returns 3 mask options\n)\n\n# Select best mask\nbest_mask = masks[np.argmax(scores)]\n```\n\n### HuggingFace Transformers\n\n```python\nimport torch\nfrom PIL import Image\nfrom transformers import SamModel, SamProcessor\n\n# Load model and processor\nmodel = SamModel.from_pretrained(\"facebook\u002Fsam-vit-huge\")\nprocessor = SamProcessor.from_pretrained(\"facebook\u002Fsam-vit-huge\")\nmodel.to(\"cuda\")\n\n# Process image with point prompt\nimage = Image.open(\"image.jpg\")\ninput_points = [[[450, 600]]]  # Batch of points\n\ninputs = processor(image, input_points=input_points, return_tensors=\"pt\")\ninputs = {k: v.to(\"cuda\") for k, v in inputs.items()}\n\n# Generate masks\nwith torch.no_grad():\n    outputs = model(**inputs)\n\n# Post-process masks to original size\nmasks = processor.image_processor.post_process_masks(\n    outputs.pred_masks.cpu(),\n    inputs[\"original_sizes\"].cpu(),\n    inputs[\"reshaped_input_sizes\"].cpu()\n)\n```\n\n## Core concepts\n\n### Model architecture\n\n```\nSAM Architecture:\n┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐\n│  Image Encoder  │────▶│ Prompt Encoder  │────▶│  Mask Decoder   │\n│     (ViT)       │     │ (Points\u002FBoxes)  │     │ (Transformer)   │\n└─────────────────┘     └─────────────────┘     └─────────────────┘\n        │                       │                       │\n   Image Embeddings      Prompt Embeddings         Masks + IoU\n   (computed once)       (per prompt)             predictions\n```\n\n### Model variants\n\n| Model | Checkpoint | Size | Speed | Accuracy |\n|-------|------------|------|-------|----------|\n| ViT-H | `vit_h` | 2.4 GB | Slowest | Best |\n| ViT-L | `vit_l` | 1.2 GB | Medium | Good |\n| ViT-B | `vit_b` | 375 MB | Fastest | Good |\n\n### Prompt types\n\n| Prompt | Description | Use Case |\n|--------|-------------|----------|\n| Point (foreground) | Click on object | Single object selection |\n| Point (background) | Click outside object | Exclude regions |\n| Bounding box | Rectangle around object | Larger objects |\n| Previous mask | Low-res mask input | Iterative refinement |\n\n## Interactive segmentation\n\nDetails, code examples and parameter tables: [references\u002Finteractive-segmentation.md](references\u002Finteractive-segmentation.md). Read it when this step applies.\n\n## Automatic mask generation\n\n### Basic automatic segmentation\n\n```python\nfrom segment_anything import SamAutomaticMaskGenerator\n\n# Create generator\nmask_generator = SamAutomaticMaskGenerator(sam)\n\n# Generate all masks\nmasks = mask_generator.generate(image)\n\n# Each mask contains:\n# - segmentation: binary mask\n# - bbox: [x, y, w, h]\n# - area: pixel count\n# - predicted_iou: quality score\n# - stability_score: robustness score\n# - point_coords: generating point\n```\n\n### Customized generation\n\n```python\nmask_generator = SamAutomaticMaskGenerator(\n    model=sam,\n    points_per_side=32,          # Grid density (more = more masks)\n    pred_iou_thresh=0.88,        # Quality threshold\n    stability_score_thresh=0.95,  # Stability threshold\n    crop_n_layers=1,             # Multi-scale crops\n    crop_n_points_downscale_factor=2,\n    min_mask_region_area=100,    # Remove tiny masks\n)\n\nmasks = mask_generator.generate(image)\n```\n\n### Filtering masks\n\n```python\n# Sort by area (largest first)\nmasks = sorted(masks, key=lambda x: x['area'], reverse=True)\n\n# Filter by predicted IoU\nhigh_quality = [m for m in masks if m['predicted_iou'] > 0.9]\n\n# Filter by stability score\nstable_masks = [m for m in masks if m['stability_score'] > 0.95]\n```\n\n## Batched inference\n\n### Multiple images\n\n```python\n# Process multiple images efficiently\nimages = [cv2.imread(f\"image_{i}.jpg\") for i in range(10)]\n\nall_masks = []\nfor image in images:\n    predictor.set_image(image)\n    masks, _, _ = predictor.predict(\n        point_coords=np.array([[500, 375]]),\n        point_labels=np.array([1]),\n        multimask_output=True\n    )\n    all_masks.append(masks)\n```\n\n### Multiple prompts per image\n\n```python\n# Process multiple prompts efficiently (one image encoding)\npredictor.set_image(image)\n\n# Batch of point prompts\npoints = [\n    np.array([[100, 100]]),\n    np.array([[200, 200]]),\n    np.array([[300, 300]])\n]\n\nall_masks = []\nfor point in points:\n    masks, scores, _ = predictor.predict(\n        point_coords=point,\n        point_labels=np.array([1]),\n        multimask_output=True\n    )\n    all_masks.append(masks[np.argmax(scores)])\n```\n\n## ONNX deployment\n\n### Export model\n\n```bash\npython scripts\u002Fexport_onnx_model.py \\\n    --checkpoint sam_vit_h_4b8939.pth \\\n    --model-type vit_h \\\n    --output sam_onnx.onnx \\\n    --return-single-mask\n```\n\n### Use ONNX model\n\n```python\nimport onnxruntime\n\n# Load ONNX model\nort_session = onnxruntime.InferenceSession(\"sam_onnx.onnx\")\n\n# Run inference (image embeddings computed separately)\nmasks = ort_session.run(\n    None,\n    {\n        \"image_embeddings\": image_embeddings,\n        \"point_coords\": point_coords,\n        \"point_labels\": point_labels,\n        \"mask_input\": np.zeros((1, 1, 256, 256), dtype=np.float32),\n        \"has_mask_input\": np.array([0], dtype=np.float32),\n        \"orig_im_size\": np.array([h, w], dtype=np.float32)\n    }\n)\n```\n\n## Common workflows\n\n### Workflow 1: Annotation tool\n\n```python\nimport cv2\n\n# Load model\npredictor = SamPredictor(sam)\npredictor.set_image(image)\n\ndef on_click(event, x, y, flags, param):\n    if event == cv2.EVENT_LBUTTONDOWN:\n        # Foreground point\n        masks, scores, _ = predictor.predict(\n            point_coords=np.array([[x, y]]),\n            point_labels=np.array([1]),\n            multimask_output=True\n        )\n        # Display best mask\n        display_mask(masks[np.argmax(scores)])\n```\n\n### Workflow 2: Object extraction\n\n```python\ndef extract_object(image, point):\n    \"\"\"Extract object at point with transparent background.\"\"\"\n    predictor.set_image(image)\n\n    masks, scores, _ = predictor.predict(\n        point_coords=np.array([point]),\n        point_labels=np.array([1]),\n        multimask_output=True\n    )\n\n    best_mask = masks[np.argmax(scores)]\n\n    # Create RGBA output\n    rgba = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)\n    rgba[:, :, :3] = image\n    rgba[:, :, 3] = best_mask * 255\n\n    return rgba\n```\n\n### Workflow 3: Medical image segmentation\n\n```python\n# Process medical images (grayscale to RGB)\nmedical_image = cv2.imread(\"scan.png\", cv2.IMREAD_GRAYSCALE)\nrgb_image = cv2.cvtColor(medical_image, cv2.COLOR_GRAY2RGB)\n\npredictor.set_image(rgb_image)\n\n# Segment region of interest\nmasks, scores, _ = predictor.predict(\n    box=np.array([x1, y1, x2, y2]),  # ROI bounding box\n    multimask_output=True\n)\n```\n\n## Output format\n\n### Mask data structure\n\n```python\n# SamAutomaticMaskGenerator output\n{\n    \"segmentation\": np.ndarray,  # H×W binary mask\n    \"bbox\": [x, y, w, h],        # Bounding box\n    \"area\": int,                 # Pixel count\n    \"predicted_iou\": float,      # 0-1 quality score\n    \"stability_score\": float,    # 0-1 robustness score\n    \"crop_box\": [x, y, w, h],    # Generation crop region\n    \"point_coords\": [[x, y]],    # Input point\n}\n```\n\n### COCO RLE format\n\n```python\nfrom pycocotools import mask as mask_utils\n\n# Encode mask to RLE\nrle = mask_utils.encode(np.asfortranarray(mask.astype(np.uint8)))\nrle[\"counts\"] = rle[\"counts\"].decode(\"utf-8\")\n\n# Decode RLE to mask\ndecoded_mask = mask_utils.decode(rle)\n```\n\n## Performance optimization\n\n### GPU memory\n\n```python\n# Use smaller model for limited VRAM\nsam = sam_model_registry[\"vit_b\"](checkpoint=\"sam_vit_b_01ec64.pth\")\n\n# Process images in batches\n# Clear CUDA cache between large batches\ntorch.cuda.empty_cache()\n```\n\n### Speed optimization\n\n```python\n# Use half precision\nsam = sam.half()\n\n# Reduce points for automatic generation\nmask_generator = SamAutomaticMaskGenerator(\n    model=sam,\n    points_per_side=16,  # Default is 32\n)\n\n# Use ONNX for deployment\n# Export with --return-single-mask for faster inference\n```\n\n## Common issues\n\n| Issue | Solution |\n|-------|----------|\n| Out of memory | Use ViT-B model, reduce image size |\n| Slow inference | Use ViT-B, reduce points_per_side |\n| Poor mask quality | Try different prompts, use box + points |\n| Edge artifacts | Use stability_score filtering |\n| Small objects missed | Increase points_per_side |\n\n## References\n\n- **[Advanced Usage](references\u002Fadvanced-usage.md)** - Batching, fine-tuning, integration\n- **[Troubleshooting](references\u002Ftroubleshooting.md)** - Common issues and solutions\n\n## Resources\n\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Fsegment-anything\n- **Paper**: https:\u002F\u002Farxiv.org\u002Fabs\u002F2304.02643\n- **Demo**: https:\u002F\u002Fsegment-anything.com\n- **SAM 2 (Video)**: https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Fsegment-anything-2\n- **HuggingFace**: https:\u002F\u002Fhuggingface.co\u002Ffacebook\u002Fsam-vit-huge\n\n## Agent operating procedure\n\n1. **Check the environment.** Confirm GPU memory, model checkpoint and licence, framework versions and input formats.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Run inference on a single sample at low resolution or short length first.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Inspect outputs qualitatively and with task metrics; check licence restrictions for generated content.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Out-of-memory on large inputs | Reduce resolution or sequence length, use half precision, or tile the input. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Check model and dataset licences before commercial or published use.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n\n## Related skills\n\n- `clip`: OpenAI's model connecting vision and language.\n- `generate-image`: Generate or edit images with AI models through the OpenRouter Image API (Gemini, Seedream, Recraft, GPT-Image, Riverflow).\n- `blip-2-vision-language`: Explains how to use Salesforce BLIP-2 (Q-Former bridging a frozen image encoder and an LLM such as OPT or FlanT5) through HuggingFace Trans…\n",{"name":5,"license":15,"metadata":52,"description":7},{"tags":53,"version":54,"category":55,"maintainer":56,"dependencies":57},"Multimodal, Image Segmentation, Computer Vision, SAM, Zero-Shot","1.0.0","multimodal-and-emerging","Kalaris Labs","segment-anything, transformers>=4.30.0, torch>=1.7.0","main","0da4485785ee599388900be50db1635489d53056",".agents\u002Fskills\u002Fkal-segment-anything-model","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6","https:\u002F\u002Fdisha6.6.thenitishkr.in\u002F","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh","www.thenitishkr","thenitishkr | AI • Cyber-security • Research\r\n","2026-11-08 03:33:25",{"source":8,"skillName":5,"commands":68,"prompt":78,"zipAvailable":79},[69,72,75],{"tool":70,"command":71},"npx","npx skills add Tashima-Tarsh\u002FDisha6.6 --skill segment-anything-model",{"tool":73,"command":74},"bunx","bunx skills add Tashima-Tarsh\u002FDisha6.6 --skill segment-anything-model",{"tool":76,"command":77},"pnpm","pnpm dlx skills add Tashima-Tarsh\u002FDisha6.6 --skill segment-anything-model","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-segment-anything-model\u002FSKILL.md",true,[81,87,91],{"path":82,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":85,"sourceHtmlUrl":86},"references\u002Fadvanced-usage.md","REFERENCE","参考文档",15803,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-segment-anything-model\u002Freferences\u002Fadvanced-usage.md",{"path":88,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":89,"sourceHtmlUrl":90},"references\u002Finteractive-segmentation.md",1598,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-segment-anything-model\u002Freferences\u002Finteractive-segmentation.md",{"path":92,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":93,"sourceHtmlUrl":94},"references\u002Ftroubleshooting.md",11914,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-segment-anything-model\u002Freferences\u002Ftroubleshooting.md",[96,123,147,172,196,220],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":103,"publishedAt":47},"01M6QRD07D4TGNDK6VJ4EHF8BV","youtube-full","Use when the user needs YouTube transcripts, video search, channel browsing, playlist extraction, or content monitoring. Trigger phrases: 'get the transcript for', 'search YouTube for', 'what are the latest videos on', 'list this playlist', 'monitor this channel', or any request involving a YouTube URL, video ID, or @handle. Do NOT use for downloading video or audio files, YouTube engagement data (likes, comments), or private\u002Fage-restricted videos.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fyoutube-full\u002FSKILL.md",[102],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,31,120,121,122],"youtube full","youtube","full","transcript","search","monitoring","data","Video","Audio","list","files","do","get","age","trigger","URL","browsing","request","youtube transcripts",{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":127,"categories":128,"keywords":129,"publishedAt":47},"01M6QRCJ3112VYPA97YG7KGMC2","x-twitter-growth","X\u002FTwitter growth engine for building audience, crafting viral content, and analyzing engagement. Use when the user wants to grow on X\u002FTwitter, write tweets or threads, analyze their X profile, research competitors on X, plan a posting strategy, or optimize engagement. Complements social-content (generic multi-platform) with X-specific depth: algorithm mechanics, thread engineering, reply strategy, profile optimization, and competitive intelligence via web search.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fx-twitter-growth\u002FSKILL.md",[],[130,131,132,133,108,134,135,136,137,138,139,140,141,142,41,143,144,145,146,31],"twitter","x twitter growth","growth","research","content","engineering","plan","web search","competitors","analyze","engine","write","strategy","platform","grow","posting","competitive",{"skillNo":148,"name":149,"nameZh":6,"description":150,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":151,"categories":152,"keywords":154,"publishedAt":47},"01M6QRBN3EHQNJY42RERP7A149","write-a-skill","Create new agent skills with proper structure, progressive disclosure, and bundled resources. Use when user wants to create, write, build, or author a new skill.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwrite-a-skill\u002FSKILL.md",[153],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[155,141,156,157,158,159,160,161,41,162,163,58,164,165,166,167,168,169,170,171],"write a skill","github","create","https","productivity","matt pocock","direct","example","build","new skill","structure","new agent","resources","with","tree","progressive disclosure","author",{"skillNo":173,"name":174,"nameZh":6,"description":175,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":176,"categories":177,"keywords":178,"publishedAt":47},"01M6QRB6G8P33PNGAF9Y69EJ9T","wrap-up","Close out a launched Claude Managed Agent — recap every primitive the founder now owns, regenerate the single-file overview page, and suggest the next 1-2 upgrades. Use when the user says \"wrap up\", \"close this out\", \"what do I own now\", \"give me the summary\", \"recap the agent\", or when the orchestrator routes phase=wrap-up. primitives_inventory.py tables everything owned (agent, environment, session, memory, outcome, deployment); overview_page.py regenerates a self-contained .\u002Fmy-agent\u002Fagent-overview.html; upgrade_suggester.py ranks the next moves from recorded deferrals plus standing hardening steps. Companion to run-without-you; the last stop before phase=done.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwrap-up\u002FSKILL.md",[],[179,180,181,182,183,184,185,186,187,41,188,115,189,190,191,192,34,193,194,195],"wrap up","up","wrap","gemini","deployment","run","file","hardening","closeout","stop","upgrade","founder","close","companion","tables","directions","phase",{"skillNo":197,"name":198,"nameZh":6,"description":199,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":200,"categories":201,"keywords":203,"publishedAt":47},"01M6QRA5AYC1RBFZ39GTWGS3N8","workflow-builder","Design and write deterministic multi-agent workflow scripts (.js files in .claude\u002Fworkflows\u002F) for Claude Code's Workflow tool. Use when a user wants to build, create, author, scaffold, or run a custom Claude Code workflow, orchestrate sub-agents (fan-out, pipeline, loop, judge-panel), or automate a repeatable multi-step task across fresh-context agents.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fworkflow-builder\u002FSKILL.md",[202],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[204,205,206,207,208,157,184,209,210,211,212,213,141,214,114,215,216,217,218,219],"workflow","workflow builder","builder","design","workflows","code","orchestrate","pipeline","loop","multi-agent","context","across","fresh","scripts","judge","claude code workflow",{"skillNo":221,"name":222,"nameZh":6,"description":223,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":224,"categories":225,"keywords":226,"publishedAt":47},"01M6QR7QMCZESKQA0ERW1E657M","weekly-review","Use when someone wants to run a weekly review, close open loops, audit stalled projects and commitments, get their system back to trusted, restart a lapsed review habit, or says \"\u002Fcs:weekly-review\". Walks David Allen's three-phase loop — GET CLEAR, GET CURRENT, GET CREATIVE — with deterministic scripts that inventory open loops, gate the checklist with named gaps, and score commitment health 0-100.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fweekly-review\u002FSKILL.md",[],[227,228,229,230,231,232,233,234,235,212,236,237,238,239,240,241,116,242,243,195],"review","weekly review","weekly","deterministic scripts","reflect","feeds","inventory","open","team","projects","project-management","scanner","conversation","back","project","sprint","cadence"]