用途
Segment Anything Model(SAM)是 Meta AI 发布的图像分割基础模型,核心特点是零样本迁移:无需针对特定图像领域或任务进行微调,即可分割图像中的任意对象。适合构建交互式标注工具、为其他视觉模型生成训练数据、构建目标检测/分割流水线,以及处理医疗、卫星等特定领域图像。
主要能力
- 零样本分割:适用于任意图像领域,无需微调。
- 灵活提示:支持前景/背景点、边界框、已有掩码,也可组合使用,并可通过追加点进行迭代优化。
- 自动分割:SamAutomaticMaskGenerator 可自动生成图中所有对象的掩码,输出包含 segmentation、bbox、area、predicted_iou、stability_score、point_coords 等字段。
- 模型规格:ViT-B(375MB,最快)、ViT-L(1.2GB,中等)、ViT-H(2.4GB,最准)。
- ONNX 导出:可部署到浏览器和边缘设备。
- 掩码可编码为 COCO RLE 格式。
使用方式
安装:
pip install git+https://github.com/facebookresearch/segment-anything.git
pip install opencv-python pycocotools matplotlib
或使用 HuggingFace transformers:pip install transformers。
下载检查点示例:
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
基础用法:通过 sam_model_registry 加载模型,用 SamPredictor.set_image 计算图像嵌入,再调用 predictor.predict 传入 point_coords、point_labels、box、mask_input 等参数获得 masks、scores、logits;multimask_output=True 时返回 3 个候选掩码。也可用 HuggingFace 的 SamModel 与 SamProcessor 加载 facebook/sam-vit-huge。
自动分割:创建 SamAutomaticMaskGenerator,可配置 points_per_side、pred_iou_thresh、stability_score_thresh、crop_n_layers、min_mask_region_area 等参数。
ONNX 部署:使用 scripts/export_onnx_model.py 导出,再用 onnxruntime 推理。
适用场景
交互式标注工具(点击生成掩码)、对象提取(生成透明背景 RGBA)、医疗图像分割(灰度转 RGB 后按 ROI 框选)、批量图像处理、以及作为 GroundingDINO 等文本提示方案的分割后端。
限制与替代
- 不提供带类别的实时目标检测,此类需求可用 YOLO/Detectron2。
- 语义/全景分割(带类别)可用 Mask2Former。
- 文本提示分割需结合 GroundingDINO + SAM。
- 视频分割应使用 SAM 2。
- 常见问题:显存不足可改用 ViT-B 或缩小图像;推理慢可减少 points_per_side;掩码质量不佳可调整提示或组合框与点;边缘伪影可用 stability_score 过滤;小目标遗漏可增大 points_per_side。
资源
GitHub:https://github.com/facebookresearch/segment-anything 论文:https://arxiv.org/abs/2304.02643 演示:https://segment-anything.com SAM 2:https://github.com/facebookresearch/segment-anything-2 HuggingFace:https://huggingface.co/facebook/sam-vit-huge