SuperAPI AI 工具集

segment-anything-model

设计与创作

查看项目

更新于 10-21 16:28

技能介绍

用途

Segment Anything Model(SAM)是 Meta AI 的图像分割基础模型,主打零样本迁移能力。当你需要在没有任务特定训练的情况下分割图像中的任意对象、构建基于点或框提示的交互式标注工具、为其他视觉模型生成训练数据,或把分割能力迁移到医学、卫星等新图像领域时,可以使用 SAM。它也可用于搭建目标检测/分割流水线。

如果需求是带类别的实时目标检测,可考虑 YOLO/Detectron2;带类别的语义/全景分割可考虑 Mask2Former;文本提示分割可考虑 GroundingDINO + SAM;视频分割可考虑 SAM 2。

主要能力

  • 零样本分割:无需微调即可用于任意图像领域。
  • 灵活提示:支持点(前景/背景)、边界框或已有掩码作为输入。
  • 自动分割:自动生成图像中所有对象的掩码。
  • 高质量:基于 1100 万张图像、11 亿个掩码训练。
  • 多种模型规模:ViT-B(最快)、ViT-L、ViT-H(最准)。
  • ONNX 导出:可部署到浏览器和边缘设备。

模型变体:ViT-H(vit_h,2.4 GB,最慢,精度最佳)、ViT-L(vit_l,1.2 GB,中等,良好)、ViT-B(vit_b,375 MB,最快,良好)。

提示类型:前景点用于选择单个对象;背景点用于排除区域;边界框用于较大对象;已有掩码用于迭代细化。

使用方式

安装:

# From GitHub
pip install git+https://github.com/facebookresearch/segment-anything.git

# Optional dependencies
pip install opencv-python pycocotools matplotlib

# Or use HuggingFace transformers
pip install transformers

下载检查点:

# ViT-H (largest, most accurate) - 2.4GB
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth

# ViT-L (medium) - 1.2GB
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth

# ViT-B (smallest, fastest) - 375MB
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth

使用 SamPredictor 的基本用法:

import numpy as np
from segment_anything import sam_model_registry, SamPredictor

# Load model
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to(device="cuda")

# Create predictor
predictor = SamPredictor(sam)

# Set image (computes embeddings once)
image = cv2.imread("image.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
predictor.set_image(image)

# Predict with point prompts
input_point = np.array([[500, 375]])  # (x, y) coordinates
input_label = np.array([1])  # 1 = foreground, 0 = background

masks, scores, logits = predictor.predict(
    point_coords=input_point,
    point_labels=input_label,
    multimask_output=True  # Returns 3 mask options
)

# Select best mask
best_mask = masks[np.argmax(scores)]

使用 HuggingFace Transformers:

import torch
from PIL import Image
from transformers import SamModel, SamProcessor

# Load model and processor
model = SamModel.from_pretrained("facebook/sam-vit-huge")
processor = SamProcessor.from_pretrained("facebook/sam-vit-huge")
model.to("cuda")

# Process image with point prompt
image = Image.open("image.jpg")
input_points = [[[450, 600]]]  # Batch of points

inputs = processor(image, input_points=input_points, return_tensors="pt")
inputs = {k: v.to("cuda") for k, v in inputs.items()}

# Generate masks
with torch.no_grad():
    outputs = model(**inputs)

# Post-process masks to original size
masks = processor.image_processor.post_process_masks(
    outputs.pred_masks.cpu(),
    inputs["original_sizes"].cpu(),
    inputs["reshaped_input_sizes"].cpu()
)

自动掩码生成:

from segment_anything import SamAutomaticMaskGenerator

# Create generator
mask_generator = SamAutomaticMaskGenerator(sam)

# Generate all masks
masks = mask_generator.generate(image)

每个掩码包含 segmentation(二值掩码)、bbox、area、predicted_iou、stability_score、point_coords 等字段。可自定义 points_per_side、pred_iou_thresh、stability_score_thresh、crop_n_layers、min_mask_region_area 等参数,并按面积、predicted_iou、stability_score 过滤。

ONNX 导出:

python scripts/export_onnx_model.py \
    --checkpoint sam_vit_h_4b8939.pth \
    --model-type vit_h \
    --output sam_onnx.onnx \
    --return-single-mask

适用场景

  • 交互式标注工具:点击前景点即时生成掩码。
  • 对象提取:按点提取对象并生成透明背景 RGBA 输出。
  • 医学图像分割:灰度转 RGB 后按 ROI 边界框分割。
  • 批量推理:多图或多提示处理,图像编码只计算一次。
  • 自动生成训练数据供其他视觉模型使用。

限制与注意事项

  • 显存不足时可改用 ViT-B 或缩小图像尺寸;推理慢时可减少 points_per_side 或使用半精度。
  • 掩码质量不佳时可尝试不同提示或框加点组合;边缘伪影可用 stability_score 过滤;小对象遗漏可增大 points_per_side。
  • 商业或公开发布前需检查模型与数据集许可。
  • 版本相关细节可能过时,应以所安装版本的官方文档为准。
  • 涉及费用、共享 GPU/云配额、个人或患者数据以及不可撤销操作时,应先征得确认。

资源

  • GitHub: https://github.com/facebookresearch/segment-anything
  • Paper: https://arxiv.org/abs/2304.02643
  • Demo: https://segment-anything.com
  • SAM 2 (Video): https://github.com/facebookresearch/segment-anything-2
  • HuggingFace: https://huggingface.co/facebook/sam-vit-huge