segment-anything README

The project's README from github.com/facebookresearch/segment-anything. As one markdown file: README.md.

Latest updates -- SAM 2: Segment Anything in Images and Videos

Please check out our new release on Segment Anything Model 2 (SAM 2).

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.

Segment Anything

Meta AI Research, FAIR

Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, Chloe Rolland, Laura Gustafson, Tete Xiao, Spencer Whitehead, Alex Berg, Wan-Yen Lo, Piotr Dollar, Ross Girshick

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

SAM design

The Segment Anything Model (SAM) 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. It has been trained on a dataset of 11 million images and 1.1 billion masks, and has strong zero-shot performance on a variety of segmentation tasks.

Installation

The code requires python>=3.8, as well as pytorch>=1.7 and torchvision>=0.8. Please follow the instructions here to install both PyTorch and TorchVision dependencies. Installing both PyTorch and TorchVision with CUDA support is strongly recommended.

Install Segment Anything:

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

or clone the repository locally and install with

git clone [email protected]:facebookresearch/segment-anything.git
cd segment-anything; pip install -e .

The following optional dependencies are necessary for mask post-processing, saving masks in COCO format, the example notebooks, and exporting the model in ONNX format. jupyter is also required to run the example notebooks.

pip install opencv-python pycocotools matplotlib onnxruntime onnx

Getting Started

First download a model checkpoint. Then the model can be used in just a few lines to get masks from a given 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>)

or generate masks for an entire image:

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>)

Additionally, masks can be generated for images from the command line:

python scripts/amg.py --checkpoint <path/to/checkpoint> --model-type <model_type> --input <image_or_folder> --output <path/to/output>

See the examples notebooks on using SAM with prompts and automatically generating masks for more details.

ONNX Export

SAM's lightweight mask decoder can be exported to ONNX format so that it can be run in any environment that supports ONNX runtime, such as in-browser as showcased in the demo. Export the model with

python scripts/export_onnx_model.py --checkpoint <path/to/checkpoint> --model-type <model_type> --output <path/to/output>

See the example notebook for details on how to combine image preprocessing via SAM's backbone with mask prediction using the ONNX model. It is recommended to use the latest stable version of PyTorch for ONNX export.

Web demo

The demo/ folder has a simple one page React app which shows how to run mask prediction with the exported ONNX model in a web browser with multithreading. Please see demo/README.md for more details.

Model Checkpoints

Three model versions of the model are available with different backbone sizes. These models can be instantiated by running

from segment_anything import sam_model_registry
sam = sam_model_registry["<model_type>"](checkpoint="<path/to/checkpoint>")

Click the links below to download the checkpoint for the corresponding model type.

Dataset

See here for an overview of the datastet. The dataset can be downloaded here. By downloading the datasets you agree that you have read and accepted the terms of the SA-1B Dataset Research License.

We save masks per image as a json file. It can be loaded as a dictionary in python in the below format.

{
    "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,            # The model's own prediction 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
}

Image ids can be found in sa_images_ids.txt which can be downloaded using the above link as well.

To decode a mask in COCO RLE format into binary:

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

See here for more instructions to manipulate masks stored in RLE format.

License

The model is licensed under the Apache 2.0 license.

Contributing

See contributing and the code of conduct.

Contributors

The Segment Anything project was made possible with the help of many contributors (alphabetical):

Aaron Adcock, Vaibhav Aggarwal, Morteza Behrooz, Cheng-Yang Fu, Ashley Gabriel, Ahuva Goldstand, Allen Goodman, Sumanth Gurram, Jiabo Hu, Somya Jain, Devansh Kukreja, Robert Kuo, Joshua Lane, Yanghao Li, Lilian Luong, Jitendra Malik, Mallika Malhotra, William Ngan, Omkar Parkhi, Nikhil Raina, Dirk Rowe, Neil Sejoor, Vanessa Stark, Bala Varadarajan, Bram Wasti, Zachary Winstrom

Citing Segment Anything

If you use SAM or SA-1B in your research, please use the following BibTeX entry.

@article{kirillov2023segany,
  title={Segment Anything},
  author={Kirillov, Alexander and Mintun, Eric and Ravi, Nikhila and Mao, Hanzi and Rolland, Chloe and Gustafson, Laura and Xiao, Tete and Whitehead, Spencer and Berg, Alexander C. and Lo, Wan-Yen and Doll{\'a}r, Piotr and Girshick, Ross},
  journal={arXiv:2304.02643},
  year={2023}
}

segment-anything (facebookresearch/segment-anything)

Searching Database…

这是什么?这是 Meta AI 推出的 Segment Anything Model(SAM),一个基础模型,可以根据点或框等提示为图像生成物体掩码,也能自动为图像中的每个物体生成掩码。
这是我需要自己训练的模型,还是只需加载的预训练检查点?这是一个 Python 代码库,用于运行 Meta 发布的预训练 SAM 检查点进行推理。你只需下载检查点,用几行代码调用模型,无需从头训练。
怎么让它跑起来?用 pip 安装该包(或克隆仓库后在本地安装),下载一个模型检查点,然后使用 SamPredictor 或 SamAutomaticMaskGenerator;也可以直接通过命令行生成掩码。
运行这个需要 PyTorch 和 GPU 吗?需要 Python 3.8+、PyTorch 1.7+ 和 torchvision 0.8+。强烈建议使用支持 CUDA 的 GPU,无论是安装依赖还是运行模型都是如此。
我现在应该用的是 SAM 的最新版本吗?这个仓库是最初的纯图像版 SAM。Meta 之后发布了 Segment Anything Model 2(SAM 2),它把分割扩展到了视频,目前是大多数新项目推荐使用的版本。
运行 SAM 必须要有独立显卡吗?强烈建议使用支持 CUDA 的 GPU,以便安装带 CUDA 支持的 PyTorch/TorchVision,并获得合理的推理速度;但这并非严格必需。
什么是 Segment Anything Model 2(SAM 2),我应该改用它吗?SAM 2 是 Meta 推出的较新基础模型,它使用带流式记忆的 Transformer,将可提示分割从图像扩展到视频,训练数据使用了规模更大的 SA-V 视频分割数据集;它位于本 README 链接的另一个仓库中。
这里提到的 SA-1B 数据集是什么?SA-1B 是用于训练 SAM 的数据集,包含 1100 万张图像和 11 亿个分割掩码,可在其独立的研究许可下下载,掩码按图像以 JSON/COCO RLE 格式存储。
SAM 能在网页浏览器中运行吗?可以。SAM 轻量级的掩码解码器可以导出为 ONNX 格式,并用任意 ONNX 运行时运行,包括 demo/ 文件夹中的 React 应用,它支持多线程,在浏览器中完成掩码预测。
我应该选哪个模型检查点?提供三种主干网络规模:ViT-H(默认,质量最高)、ViT-L 和 ViT-B,每种都可以作为单独的检查点文件下载。
Size
18.3 MB
Stars
55K
Updated
CommitSep 18
Age
3y
Commits · 90 Days