sam2

facebookresearchApache-2.0更新放缓

Meta 开源的 SAM 2 图像与视频通用分割模型,提供推理代码、预训练权重下载和示例 notebook,可对任意画面中的物体做可提示分割与视频目标跟踪。

The repository provides code for running inference with the Meta Segment Anything Model 2 (SAM 2), links for downloading the trained model checkpoints, and example notebooks that show how to use the model.

暂无版本20,128star +15 / 7 天2,588fork同步于 2026-11-10 11:24 UTC

怎么上手

由 README 提炼,执行前请确认
git clone https://github.com/facebookresearch/sam2.git && cd sam2
pip install -e .
cd checkpoints && ./download_ckpts.sh && cd ..
硬件要求按 README 说明

README 未给出显存要求;安装说明面向 GPU 机器,示例用 CUDA 与 bfloat16 推理,并需 nvcc 编译自定义 CUDA kernel,未说明支持的 GPU 厂商与型号

支持 Apple Silicon需要 CUDA
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

Meta 的 SAM 2 图像与视频可提示分割基础模型,支持点击或框提示并跨视频帧追踪目标

Meta 开源的 SAM 2 图像与视频通用分割模型,提供推理代码、预训练权重下载和示例 notebook,可对任意画面中的物体做可提示分割与视频目标跟踪。

核心能力

  • 用流式记忆的 Transformer 架构实现实时视频分割
  • 支持点击或框提示,并在视频中逐帧传播掩码
  • 提供 SAM2ImagePredictor 与 SAM2VideoPredictor 两套 API
  • 支持多目标追踪,可在追踪开始后新增目标
  • 支持 torch.compile 全模型加速视频推理

容易踩的坑

需 python>=3.10、torch>=2.5.1、torchvision>=0.20.1,低版本会被 pip 尝试升级;安装需 nvcc 编译 CUDA 扩展,缺失时需装匹配 PyTorch CUDA 版本的 CUDA toolkit;使用前必须单独下载模型 checkpoint,或用 huggingface_hub 从 Hugging Face 加载

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

0 个版本

暂无 release 数据(可能没有发版,或尚未同步)。

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    SAM 2: Segment Anything in Images and Videos

    AI at Meta, FAIR

    Nikhila Ravi, Valentin Gabeur, Yuan-Ting Hu, Ronghang Hu, Chaitanya Ryali, Tengyu Ma, Haitham Khedr, Roman Rädle, Chloe Rolland, Laura Gustafson, Eric Mintun, Junting Pan, Kalyan Vasudev Alwala, Nicolas Carion, Chao-Yuan Wu, Ross Girshick, Piotr Dollár, Christoph Feichtenhofer

    [Paper] [Project] [Demo] [Dataset] [Blog] [BibTeX]

    SAM 2 architecture

    Segment Anything Model 2 (SAM 2) is a foundation model towards solving promptable visual segmentation in images and videos. We extend SAM to video by considering images as a video with a single frame. The model design is a simple transformer architecture with streaming memory for real-time video processing. We build a model-in-the-loop data engine, which improves model and data via user interaction, to collect our SA-V dataset, the largest video segmentation dataset to date. SAM 2 trained on our data provides strong performance across a wide range of tasks and visual domains.

    SA-V dataset

    Latest updates

    12/11/2024 -- full model compilation for a major VOS speedup and a new SAM2VideoPredictor to better handle multi-object tracking

    • We now support torch.compile of the entire SAM 2 model on videos, which can be turned on by setting vos_optimized=True in build_sam2_video_predictor, leading to a major speedup for VOS inference.
    • We update the implementation of SAM2VideoPredictor to support independent per-object inference, allowing us to relax the assumption of prompting for multi-object tracking and adding new objects after tracking starts.
    • See RELEASE_NOTES.md for full details.

    09/30/2024 -- SAM 2.1 Developer Suite (new checkpoints, training code, web demo) is released

    • A new suite of improved model checkpoints (denoted as SAM 2.1) are released. See Model Description for details.
      • To use the new SAM 2.1 checkpoints, you need the latest model code from this repo. If you have installed an earlier version of this repo, please first uninstall the previous version via pip uninstall SAM-2, pull the latest code from this repo (with git pull), and then reinstall the repo following Installation below.
    • The training (and fine-tuning) code has been released. See training/README.md on how to get started.
    • The frontend + backend code for the SAM 2 web demo has been released. See demo/README.md for details.

    Installation

    SAM 2 needs to be installed first before use. The code requires python>=3.10, as well as torch>=2.5.1 and torchvision>=0.20.1. Please follow the instructions here to install both PyTorch and TorchVision dependencies. You can install SAM 2 on a GPU machine using:

    git clone https://github.com/facebookresearch/sam2.git && cd sam2
    
    pip install -e .
    

    If you are installing on Windows, it's strongly recommended to use Windows Subsystem for Linux (WSL) with Ubuntu.

    To use the SAM 2 predictor and run the example notebooks, jupyter and matplotlib are required and can be installed by:

    pip install -e ".[notebooks]"
    

    Note:

    1. It's recommended to create a new Python environment via Anaconda for this installation and install PyTorch 2.5.1 (or higher) via pip following https://pytorch.org/. If you have a PyTorch version lower than 2.5.1 in your current environment, the installation command above will try to upgrade it to the latest PyTorch version using pip.
    2. The step above requires compiling a custom CUDA kernel with the nvcc compiler. If it isn't already available on your machine, please install the CUDA toolkits with a version that matches your PyTorch CUDA version.
    3. If you see a message like Failed to build the SAM 2 CUDA extension during installation, you can ignore it and still use SAM 2 (some post-processing functionality may be limited, but it doesn't affect the results in most cases).

    Please see INSTALL.md for FAQs on potential issues and solutions.

    Getting Started

    Download Checkpoints

    First, we need to download a model checkpoint. All the model checkpoints can be downloaded by running:

    cd checkpoints && \
    ./download_ckpts.sh && \
    cd ..
    

    or individually from:

    (note that these are the improved checkpoints denoted as SAM 2.1; see Model Description for details.)

    Then SAM 2 can be used in a few lines as follows for image and video prediction.

    Image prediction

    SAM 2 has all the capabilities of SAM on static images, and we provide image prediction APIs that closely resemble SAM for image use cases. The SAM2ImagePredictor class has an easy interface for image prompting.

    import torch
    from sam2.build_sam import build_sam2
    from sam2.sam2_image_predictor import SAM2ImagePredictor
    
    checkpoint = "./checkpoints/sam2.1_hiera_large.pt"
    model_cfg = "configs/sam2.1/sam2.1_hiera_l.yaml"
    predictor = SAM2ImagePredictor(build_sam2(model_cfg, checkpoint))
    
    with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
        predictor.set_image(<your_image>)
        masks, _, _ = predictor.predict(<input_prompts>)
    

    Please refer to the examples in image_predictor_example.ipynb (also in Colab here) for static image use cases.

    SAM 2 also supports automatic mask generation on images just like SAM. Please see automatic_mask_generator_example.ipynb (also in Colab here) for automatic mask generation in images.

    Video prediction

    For promptable segmentation and tracking in videos, we provide a video predictor with APIs for example to add prompts and propagate masklets throughout a video. SAM 2 supports video inference on multiple objects and uses an inference state to keep track of the interactions in each video.

    import torch
    from sam2.build_sam import build_sam2_video_predictor
    
    checkpoint = "./checkpoints/sam2.1_hiera_large.pt"
    model_cfg = "configs/sam2.1/sam2.1_hiera_l.yaml"
    predictor = build_sam2_video_predictor(model_cfg, checkpoint)
    
    with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
        state = predictor.init_state(<your_video>)
    
        # add new prompts and instantly get the output on the same frame
        frame_idx, object_ids, masks = predictor.add_new_points_or_box(state, <your_prompts>):
    
        # propagate the prompts to get masklets throughout the video
        for frame_idx, object_ids, masks in predictor.propagate_in_video(state):
            ...
    

    Please refer to the examples in video_predictor_example.ipynb (also in Colab here) for details on how to add click or box prompts, make refinements, and track multiple objects in videos.

    Load from 🤗 Hugging Face

    Alternatively, models can also be loaded from Hugging Face (requires pip install huggingface_hub).

    For image prediction:

    import torch
    from sam2.sam2_image_predictor import SAM2ImagePredictor
    
    predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2-hiera-large")
    
    with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
        predictor.set_image(<your_image>)
        masks, _, _ = predictor.predict(<input_prompts>)
    

    For video prediction:

    import torch
    from sam2.sam2_video_predictor import SAM2VideoPredictor
    
    predictor = SAM2VideoPredictor.from_pretrained("facebook/sam2-hiera-large")
    
    with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
        state = predictor.init_state(<your_video>)
    
        # add new prompts and instantly get the output on the same frame
        frame_idx, object_ids, masks = predictor.add_new_points_or_box(state, <your_prompts>):
    
        # propagate the prompts to get masklets throughout the video
        for frame_idx, object_ids, masks in predictor.propagate_in_video(state):
            ...
    

    Model Description

    SAM 2.1 checkpoints

    The table below shows the improved SAM 2.1 checkpoints released on September 29, 2024.

    ModelSize (M)Speed (FPS)SA-V test (J&F)MOSE val (J&F)LVOS v2 (J&F)
    sam2.1_hiera_tiny (config, checkpoint)38.991.276.571.877.3
    sam2.1_hiera_small (config, checkpoint)4684.876.673.578.3
    sam2.1_hiera_base_plus (config, checkpoint)80.864.178.273.778.2
    sam2.1_hiera_large (config, checkpoint)224.439.579.574.680.6

    SAM 2 checkpoints

    The previous SAM 2 checkpoints released on July 29, 2024 can be found as follows:

    ModelSize (M)Speed (FPS)SA-V test (J&F)MOSE val (J&F)LVOS v2 (J&F)
    sam2_hiera_tiny (config, checkpoint)38.991.575.070.975.3
    sam2_hiera_small (config, checkpoint)4685.674.971.576.4
    sam2_hiera_base_plus (config, checkpoint)80.864.874.772.875.8
    sam2_hiera_large (config, checkpoint)224.439.776.074.679.8

    Speed measured on an A100 with torch 2.5.1, cuda 12.4. See benchmark.py for an example on benchmarking (compiling all the model components). Compiling only the image encoder can be more flexible and also provide (a smaller) speed-up (set compile_image_encoder: True in the config).

    Segment Anything Video Dataset

    See sav_dataset/README.md for details.

    Training SAM 2

    You can train or fine-tune SAM 2 on custom datasets of images, videos, or both. Please check the training README on how to get started.

    Web demo for SAM 2

    We have released the frontend + backend code for the SAM 2 web demo (a locally deployable version similar to https://sam2.metademolab.com/demo). Please see the web demo README for details.

    License

    The SAM 2 model checkpoints, SAM 2 demo code (front-end and back-end), and SAM 2 training code are licensed under Apache 2.0, however the Inter Font and Noto Color Emoji used in the SAM 2 demo code are made available under the SIL Open Font License, version 1.1.

    Contributing

    See contributing and the code of conduct.

    Contributors

    The SAM 2 project was made possible with the help of many contributors (alphabetical):

    Karen Bergan, Daniel Bolya, Alex Bosenberg, Kai Brown, Vispi Cassod, Christopher Chedeau, Ida Cheng, Luc Dahlin, Shoubhik Debnath, Rene Martinez Doehner, Grant Gardner, Sahir Gomez, Rishi Godugu, Baishan Guo, Caleb Ho, Andrew Huang, Somya Jain, Bob Kamma, Amanda Kallet, Jake Kinney, Alexander Kirillov, Shiva Koduvayur, Devansh Kukreja, Robert Kuo, Aohan Lin, Parth Malani, Jitendra Malik, Mallika Malhotra, Miguel Martin, Alexander Miller, Sasha Mitts, William Ngan, George Orlin, Joelle Pineau, Kate Saenko, Rodrick Shepard, Azita Shokrpour, David Soofian, Jonathan Torres, Jenny Truong, Sagar Vaze, Meng Wang, Claudette Ward, Pengchuan Zhang.

    Third-party code: we use a GPU-based connected component algorithm adapted from cc_torch (with its license in LICENSE_cctorch) as an optional post-processing step for the mask predictions.

    Citing SAM 2

    If you use SAM 2 or the SA-V dataset in your research, please use the following BibTeX entry.

    @article{ravi2024sam2,
      title={SAM 2: Segment Anything in Images and Videos},
      author={Ravi, Nikhila and Gabeur, Valentin and Hu, Yuan-Ting and Hu, Ronghang and Ryali, Chaitanya and Ma, Tengyu and Khedr, Haitham and R{\"a}dle, Roman and Rolland, Chloe and Gustafson, Laura and Mintun, Eric and Pan, Junting and Alwala, Kalyan Vasudev and Carion, Nicolas and Wu, Chao-Yuan and Girshick, Ross and Doll{\'a}r, Piotr and Feichtenhofer, Christoph},
      journal={arXiv preprint arXiv:2408.00714},
      url={https://arxiv.org/abs/2408.00714},
      year={2024}
    }