Loading...

文章背景图

Segment Anything (SAM) 保姆级部署教程:Meta 开源图像分割基础模型,几行代码自动分割一切物体

2026-11-02
0
- 字
- 分钟
|

本文所有命令与配置均照搬 facebookresearch/segment-anything 官方仓库 README(main 分支)原文,未作任何改动与发挥。信息核验日期:2026-11-01。

一、项目介绍

Segment Anything Model (SAM) 是 Meta AI Research(FAIR)开源的图像分割基础模型(官方 README 定位:"produces high quality object masks from input prompts such as points or boxes, and it can be used to generate masks for all objects in an image")。它在一个包含 1100 万张图像、11 亿个掩码的数据集(SA-1B)上训练,对各种分割任务具备强零样本(zero-shot)能力。

输入一个点或一个框,SAM 就能输出高质量的物体掩码;也可以对整张图自动生成所有物体的掩码。官方同时提供了网页 demo(https://segment-anything.com/demo )与 ONNX 导出能力,可在浏览器中运行。

项目在 GitHub(facebookresearch/segment-anything)持续活跃维护(核验日期 2026-11-01);官方 README 顶部已声明 SAM 的后续版本是 SAM 2(https://github.com/facebookresearch/segment-anything-2 ),但 SAM 1 仓库仍独立维护、文档完整。

二、功能拆解

按官方 README,SAM 核心能力:

功能 说明
Promptable Segmentation 输入点(point)或框(box),输出对应物体的高质量掩码
Automatic Mask Generation 对整张图自动生成所有物体的掩码(SamAutomaticMaskGenerator)
三种 backbone 尺寸 ViT-H(默认最大)、ViT-L、ViT-B,精度/速度可权衡
ONNX 导出 将轻量 mask decoder 导出 ONNX,可在浏览器/ONNX Runtime 环境运行
命令行批处理 scripts/amg.py 对图片或目录批量自动生成掩码
Notebook 示例 predictor_example.ipynb、automatic_mask_generator_example.ipynb、onnx_model_example.ipynb
Web demo demo/ 目录提供 React 单页应用,用导出的 ONNX 模型在浏览器跑
数据集 SA-1B 数据集(11M 图、1.1B 掩码),独立 Research License

三、官方/GitHub 链接

  • GitHub 仓库:https://github.com/facebookresearch/segment-anything
  • 项目主页:https://segment-anything.com/
  • 在线 Demo:https://segment-anything.com/demo
  • 论文:https://ai.facebook.com/research/publications/segment-anything/
  • 数据集下载:https://ai.facebook.com/datasets/segment-anything-downloads/
  • SAM 2(后续版本):https://github.com/facebookresearch/segment-anything-2
  • PyTorch 安装指引:https://pytorch.org/get-started/locally/

四、环境要求

官方 README「Installation」明确:

  • Python:≥ 3.8("The code requires python>=3.8")
  • PyTorch:≥ 1.7("as well as pytorch>=1.7")
  • torchvision:≥ 0.8("and torchvision>=0.8")
  • 强烈建议安装带 CUDA 支持的 PyTorch 与 TorchVision(官方原文:"Installing both PyTorch and TorchVision with CUDA support is strongly recommended")
  • 可选依赖(mask 后处理、COCO 格式保存、notebook、ONNX 导出需要):opencv-python、pycocotools、matplotlib、onnxruntime、onnx、jupyter
  • 模型权重: 三个 checkpoint 体积较大(ViT-H 约 2.4GB),需预留磁盘空间
  • 操作系统: 官方未限定;Linux/macOS 均可;Windows 通过 WSL 更稳妥(官方未明确写 Windows,故不强行推荐)

五、部署步骤

步骤 1:安装 PyTorch 与 TorchVision

按官方指向的 https://pytorch.org/get-started/locally/ 安装匹配本机 CUDA 版本的 PyTorch ≥1.7 与 torchvision ≥0.8(官方未给具体 pip 命令,以 PyTorch 官网为准)。

步骤 2:安装 Segment Anything(官方原命令二选一)

方式 A——从 GitHub 直接 pip 安装:

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

逐段解释:pip install git+https://... 直接从 GitHub main 分支拉源码并安装为 Python 包;适合仅作为库调用、不需要改源码的场景。

方式 B——克隆仓库后 editable 安装:

git clone git@github.com:facebookresearch/segment-anything.git
cd segment-anything; pip install -e .

逐段解释:git clone 克隆仓库(用 SSH 地址;HTTPS 等价为 https://github.com/facebookresearch/segment-anything.git);cd segment-anything 进入仓库;pip install -e . 以 editable 模式安装,改源码立即生效。

预期输出参考: pip 解析并安装 segment-anything 包,结束时输出 Successfully installed segment-anything-xxx。

步骤 3:安装可选依赖(官方原命令)

pip install opencv-python pycocotools matplotlib onnxruntime onnx

逐段解释:这是官方明确列出的"mask post-processing, saving masks in COCO format, the example notebooks, and exporting the model in ONNX format"所需依赖;跑 notebook 还需 jupyter。

预期输出参考: pip 安装上述 5 个包及依赖。

步骤 4:下载模型 checkpoint(官方原文链接)

在浏览器或命令行下载三选一:

  • ViT-H(默认,最大最准): https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
  • ViT-L: https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth
  • ViT-B(最小最快): https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth

例如用 wget 下载 ViT-H:

wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth

预期输出参考: wget 下载进度条,结束时得到对应 .pth 文件。

六、配置参数详解

1. 模型类型 registry(官方原文)

from segment_anything import sam_model_registry
sam = sam_model_registry["<model_type>"](checkpoint="<path/to/checkpoint>")
model_type 取值 对应 backbone 对应 checkpoint
default 或 vit_h ViT-H sam_vit_h_4b8939.pth
vit_l ViT-L sam_vit_l_0b3195.pth
vit_b ViT-B sam_vit_b_01ec64.pth

2. 推理 API(官方 Getting Started 原文)

Prompt 模式(点/框提示):

from segment_anything import SamPredictor, sam_model_registry
sam = sam_model_registry["<model_type>"](checkpoint="<path/to/checkpoint>")
predictor = SamPredictor(sam)
predictor.set_image(<your_image>)
masks, _, _ = predictor.predict(<input_prompts>)

自动掩码生成模式:

from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
sam = sam_model_registry["<model_type>"](checkpoint="<path/to/checkpoint>")
mask_generator = SamAutomaticMaskGenerator(sam)
masks = mask_generator.generate(<your_image>)

3. 数据集掩码 JSON 格式(官方原文)

{
    "image"                 : image_info,
    "annotations"           : [annotation],
}

image_info {
    "image_id"              : int,              # Image id
    "width"                 : int,              # Image width
    "height"                : int,              # Image height
    "file_name"             : str,              # Image filename
}

annotation {
    "id"                    : int,              # Annotation id
    "segmentation"          : dict,             # Mask saved in COCO RLE format.
    "bbox"                  : [x, y, w, h],     # The box around the mask, in XYWH format
    "area"                  : int,              # The area in pixels of the mask
    "predicted_iou"         : float,            # A measure of the mask's quality
    "stability_score"       : float,            # A measure of the mask's quality
    "crop_box"              : [x, y, w, h],     # The crop of the image used to generate the mask, in XYWH format
    "point_coords"          : [[x, y]],         # The point coordinates input to the model to generate the mask
}

COCO RLE 解码(官方原文):

from pycocotools import mask as mask_utils
mask = mask_utils.decode(annotation["segmentation"])

七、启动与运维

SAM 是 Python 库,没有独立服务。官方 README 给出的入口:

  • Prompt 推理: SamPredictor(见第六节)。
  • 自动掩码推理: SamAutomaticMaskGenerator。
  • 命令行批量处理(官方原命令):
python scripts/amg.py --checkpoint <path/to/checkpoint> --model-type <model_type> --input <image_or_folder> --output <path/to/output>

逐段解释:--checkpoint 指定下载的权重路径;--model-type 取 default/vit_l/vit_b;--input 单张图或目录;--output 输出目录。

  • ONNX 导出(官方原命令):
python scripts/export_onnx_model.py --checkpoint <path/to/checkpoint> --model-type <model_type> --output <path/to/output>

逐段解释:把 SAM 轻量 mask decoder 导出为 ONNX;官方建议用最新稳定版 PyTorch 做导出。

  • Web demo: demo/ 目录是 React 单页应用,详见 demo/README.md(https://github.com/facebookresearch/segment-anything/blob/main/demo/README.md )。
  • 后台常驻 / 开机自启: 官方 README 未提供任何 systemd/Docker/supervisor 方案——SAM 不是服务型软件。
  • 修改端口: 不涉及。
  • 数据持久化: 模型 .pth 权重保存在本地路径;输出掩码按 --output 或脚本指定路径写入。

八、实操验证

  1. 完成第二、三、四步安装与权重下载后,启动 Python:
python
  1. 加载 ViT-H 模型并对一张图做 Prompt 分割(按官方 Getting Started):
from segment_anything import SamPredictor, sam_model_registry
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
predictor = SamPredictor(sam)
  1. 加载图片并编码:
import cv2
image = cv2.imread("your_image.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
predictor.set_image(image)
  1. 给出一个点提示,预测掩码:
masks, scores, logits = predictor.predict(
    point_coords=np.array([[100, 100]]),
    point_labels=np.array([1]),
)
  1. 验证自动掩码生成:
from segment_anything import SamAutomaticMaskGenerator
mask_generator = SamAutomaticMaskGenerator(sam)
masks = mask_generator.generate(image)
print(len(masks))   # 输出检测到的物体个数

预期看到: Python 不报错,masks 为 bool 形状的 ndarray;len(masks) 为正整数。官方 README 未给出具体输出数字,不虚构。

  1. 命令行批处理验证:
python scripts/amg.py --checkpoint sam_vit_h_4b8939.pth --model-type vit_h --input your_image.jpg --output output_dir

预期看到: output_dir/ 下生成对应掩码文件。

九、故障排查

案例 1:ModuleNotFoundError: No module named 'segment_anything'

  • 报错原因:未按步骤 2 安装,或在另一个 Python 环境执行。
  • 分步解决:① python -c "import sys; print(sys.executable)" 确认 Python 路径;② 在同一环境执行 pip install git+https://github.com/facebookresearch/segment-anything.git;③ 重新 import segment_anything。

案例 2:AssertionError: Torch not compiled with CUDA enabled 或 CUDA 版本不匹配

  • 报错原因:官方强烈建议安装带 CUDA 支持的 PyTorch("Installing both PyTorch and TorchVision with CUDA support is strongly recommended");CPU 版本只能 CPU 推理,极慢。
  • 分步解决:① 卸载现有 torch:pip uninstall torch torchvision;② 按 https://pytorch.org/get-started/locally/ 选择匹配本机 CUDA 的命令重装;③ 验证 python -c "import torch; print(torch.cuda.is_available())" 应输出 True。

案例 3:FileNotFoundError: sam_vit_h_4b8939.pth 或 checkpoint 加载失败

  • 报错原因:未下载权重或路径不对。
  • 分步解决:① 确认 wget 下载完成;② 用绝对路径传给 checkpoint=;③ 校验文件大小(ViT-H 约 2.4GB,下载中断需重下)。

案例 4:import pycocotools 失败 / Windows 上编译错误

  • 报错原因:未执行步骤 3 安装可选依赖;Windows 上 pycocotools 编译需要 C++ 构建工具。
  • 分步解决:① 执行 pip install opencv-python pycocotools matplotlib onnxruntime onnx;② Windows 用户建议用 WSL(官方未明确写,但 SAM 2 文档明确推荐 WSL;SAM 1 同理)。

十、升级、回滚与卸载

升级:

pip install --upgrade git+https://github.com/facebookresearch/segment-anything.git

editable 安装者:在仓库内 git pull 即可(源码即最新)。

回滚: 官方未提供一键回滚;可 git checkout <旧tag/commit> 后重新 pip install -e .。

卸载:

pip uninstall segment-anything

删除下载的 .pth 权重文件即清除模型权重(官方未提供清理命令,此为通用清理)。

十一、商用许可合规说明

  • 许可证:Apache License 2.0(仓库根 LICENSE 文件首行确认;官方 README「License」一节原文:"The model is licensed under the Apache 2.0 license")。
  • Apache-2.0 允许自由使用、修改、分发与商用;分发时须保留版权声明与许可文本,修改过的文件须标注变更。
  • 注意数据集许可: SA-1B 数据集(https://ai.facebook.com/datasets/segment-anything-downloads/ )采用独立的 SA-1B Dataset Research License,官方明确:"By downloading the datasets you agree that you have read and accepted the terms of the SA-1B Dataset Research License"——该数据集仅限研究用途,不得商用;但 SAM 模型权重与代码本身是 Apache-2.0,可商用。
  • 商用部署 SAM 模型本身无需付费授权;如基于 SA-1B 二次训练衍生模型,须自行评估数据集许可。
评论交流

文章目录