Archive of AI

Source Snapshot / 2024-07-29-meta-sam-2-2

SAM 2 官方代码与权重许可

Linked event: 2024-07-29 · Meta Open-Sources Real-Time Image and Video Segmentation Model SAM 2 Under Apache 2.0

Publisher
Facebook Research/GitHub
Archived
2026-11-23
Capture Method
Direct page capture
HTTP / SHA-256
200 / fecffb4e84f2bc97
Original URL
Open source ↗
Wayback Backup
Not archived
This page preserves a plain-text static snapshot against link rot. When citing figures, tables, or full legal terms, verify against the original URL and Wayback Machine archive.

[来源关键摘录] 官方仓库说明流式视频分割设计,并明确模型检查点和代码采用 Apache 2.0。

[正文前段节选] Skip to content

Navigation Menu

Appearance settings

You signed in with another tab or window. Reload to refresh your session.

You signed out in another tab or window. Reload to refresh your session.

You switched accounts on another tab or window. Reload to refresh your session.

Dismiss alert

{{ message }}

Repository navigation

NotificationsYou must be signed in to change notification settings

Fork2.6k (2.6k)

Star20.2k (20.2k)You must be signed in to star a repository

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.

Apache-2.0, BSD-3-Clause licenses found

Code of conduct

Contributing

Security policy

Custom properties

111 watching

Report repository

BranchesTags

Open more actions menu

Latest commit

Folders and files

Last commit message

Last commit date

.github/workflows

.clang-format

.watchmanconfig

CODE_OF_CONDUCT.md

CONTRIBUTING.md

LICENSE_cctorch

RELEASE_NOTES.md

backend.Dockerfile

docker-compose.yaml

pyproject.toml

View all files

Repository files navigation

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]

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.

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]"

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.

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.

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 && \

or individually from:

sam2.1_hiera_tiny.pt

sam2.1_hiera_small.pt

sam2.1_hiera_base_plus.pt

sam2.1_hiera_large.pt

(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.

from sam2.build_sam import build_sam2_video_predictor

predictor = build_sam2_video_predictor(model_cfg, checkpoint)

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:

predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2-hiera-large")

For video prediction:

from sam2.sam2_video_predictor import SAM2VideoPredictor

predictor = SAM2VideoPredictor.from_pretrained("facebook/sam2-hiera-large")

Model Description

SAM 2.1 checkpoints

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

SA-V test (J&F)

MOSE val (J&F)

LVOS v2 (J&F)

sam2.1_hiera_tiny (config, checkpoint)

[...内容已截断,完整版请查看原文或 Wayback 快照]