Convert Figma logo to code with AI

IDEA-Research logoGrounded-Segment-Anything

Grounded SAM: Marrying Grounding DINO with Segment Anything & Stable Diffusion & Recognize Anything - Automatically Detect , Segment and Generate Anything

14,706
1,362
14,706
278

Top Related Projects

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

7,333

Fast Segment Anything

3,634

Segment Anything in High Quality [NeurIPS 2023]

This is the official code for MobileSAM project that makes SAM lightweight for mobile applications and beyond!

EfficientSAM: Leveraged Masked Image Pretraining for Efficient Segment Anything

Quick Overview

Grounded-Segment-Anything is a project that combines Grounding DINO for object detection and Segment Anything Model (SAM) for segmentation. It aims to create a powerful, flexible system for detecting, segmenting, and analyzing objects in images with minimal user input.

Pros

  • Combines state-of-the-art object detection and segmentation models
  • Highly flexible and adaptable to various use cases
  • Supports both text-prompted and interactive object detection/segmentation
  • Provides pre-trained models for quick implementation

Cons

  • Requires significant computational resources for optimal performance
  • May have limitations in real-time applications due to processing time
  • Depends on multiple external libraries and models
  • Potential for occasional inaccuracies in complex scenes or with ambiguous prompts

Code Examples

  1. Basic object detection and segmentation:
from groundingdino.util.inference import load_model, load_image, predict, annotate
from segment_anything import sam_model_registry, SamPredictor

# Load models
grounding_dino_model = load_model("groundingdino_swint_ogc.pth")
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")

# Perform detection and segmentation
image = load_image("example.jpg")
boxes, logits, phrases = predict(grounding_dino_model, image, "cat")
sam_predictor = SamPredictor(sam)
sam_predictor.set_image(image)
masks, _, _ = sam_predictor.predict(box=boxes[0])

# Visualize results
annotated_frame = annotate(image, boxes, logits, phrases)
  1. Interactive object selection:
import cv2
from segment_anything import SamAutomaticMaskGenerator

# Load SAM model
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
mask_generator = SamAutomaticMaskGenerator(sam)

# Generate all possible masks
image = cv2.imread("example.jpg")
masks = mask_generator.generate(image)

# Interactive selection (simplified example)
def on_mouse_click(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        for mask in masks:
            if mask["segmentation"][y, x]:
                cv2.imshow("Selected Mask", mask["segmentation"].astype(float))
                break

cv2.imshow("Image", image)
cv2.setMouseCallback("Image", on_mouse_click)
cv2.waitKey(0)
  1. Combining with CLIP for zero-shot classification:
import torch
from PIL import Image
import clip

# Load CLIP model
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)

# Perform segmentation (assuming 'masks' is obtained from previous steps)
image = Image.open("example.jpg")
for mask in masks:
    masked_image = Image.fromarray(image * mask["segmentation"][:, :, None])
    image_input = preprocess(masked_image).unsqueeze(0).to(device)
    text_inputs = torch.cat([clip.tokenize(f"a photo of a {c}") for c in ["cat", "dog", "bird"]]).to(device)
    
    with torch.no_grad():
        image_features = model.encode_image(image_input)
        text_features = model.encode_text(text_inputs)
        similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
    
    print(f"Segment classification: {similarity[0]}")

Getting Started

  1. Clone the repository:

    git clone https://github.com/IDEA-Research/Grounded-Segment-Anything.git
    cd Grounded-Segment-Anything
    
  2. Install

Competitor Comparisons

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

Pros of Segment Anything

  • More established and widely adopted in the computer vision community
  • Extensive documentation and examples for various use cases
  • Highly optimized for performance and efficiency

Cons of Segment Anything

  • Limited to image segmentation tasks without additional context
  • Requires manual prompting or interaction for specific object segmentation
  • Less flexible for integrating with other AI models or tasks

Code Comparison

Segment Anything:

from segment_anything import SamPredictor, sam_model_registry

sam = sam_model_registry["default"](checkpoint="sam_vit_h_4b8939.pth")
predictor = SamPredictor(sam)
predictor.set_image(image)
masks, _, _ = predictor.predict(point_coords=input_point, point_labels=input_label)

Grounded-Segment-Anything:

from grounded_sam import GroundedSAM

grounded_sam = GroundedSAM(sam_checkpoint="sam_vit_h_4b8939.pth", grounding_dino_checkpoint="groundingdino_swint_ogc.pth")
masks, boxes, phrases = grounded_sam.predict_image(image, text_prompt="Find all objects")

The main difference is that Grounded-Segment-Anything combines SAM with GroundingDINO, allowing for text-prompted object detection and segmentation in a single step, while Segment Anything requires manual input for specific object segmentation.

7,333

Fast Segment Anything

Pros of FastSAM

  • Significantly faster inference speed, achieving real-time performance
  • Lighter model architecture, requiring less computational resources
  • Simpler implementation and easier to integrate into existing projects

Cons of FastSAM

  • Potentially lower segmentation accuracy compared to Grounded-Segment-Anything
  • Limited support for complex scene understanding and object relationships
  • May struggle with fine-grained segmentation tasks

Code Comparison

FastSAM:

from fastsam import FastSAM, FastSAMPrompt

model = FastSAM('FastSAM-x.pt')
everything_results = model(image, device='cuda')
prompt_process = FastSAMPrompt(image, everything_results, device='cuda')

Grounded-Segment-Anything:

from segment_anything import sam_model_registry, SamPredictor
from groundingdino.util.inference import load_model, load_image, predict

sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
sam.to(device=device)
predictor = SamPredictor(sam)

Both repositories provide efficient image segmentation solutions, but FastSAM focuses on speed and lightweight implementation, while Grounded-Segment-Anything offers more advanced features for complex segmentation tasks and scene understanding.

3,634

Segment Anything in High Quality [NeurIPS 2023]

Pros of sam-hq

  • Focuses on high-quality segmentation, potentially offering better accuracy for detailed objects
  • Designed specifically for high-resolution images, which may be beneficial for certain applications
  • Implements a more efficient transformer architecture, potentially leading to faster processing times

Cons of sam-hq

  • More specialized use case, primarily targeting high-resolution images
  • May require more computational resources due to its focus on high-quality segmentation
  • Potentially less versatile compared to Grounded-Segment-Anything's broader approach

Code Comparison

sam-hq:

sam_hq = sam_model_registry[args.model_type](checkpoint=args.checkpoint)
sam_hq.to(device=args.device)
predictor = SamPredictor(sam_hq)

Grounded-Segment-Anything:

sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to(device=device)
mask_generator = SamAutomaticMaskGenerator(sam)

Both repositories use similar initialization patterns for their respective models, but sam-hq focuses on high-quality predictions while Grounded-Segment-Anything offers a more general-purpose approach with automatic mask generation.

This is the official code for MobileSAM project that makes SAM lightweight for mobile applications and beyond!

Pros of MobileSAM

  • Significantly smaller model size, making it more suitable for mobile and edge devices
  • Faster inference time, allowing for real-time segmentation on resource-constrained hardware
  • Simpler architecture, potentially easier to integrate and deploy in various applications

Cons of MobileSAM

  • May have lower segmentation accuracy compared to Grounded-Segment-Anything, especially for complex scenes
  • Limited to image segmentation tasks, while Grounded-Segment-Anything offers additional functionalities like grounding and multi-modal capabilities
  • Potentially less robust in handling diverse and challenging scenarios

Code Comparison

MobileSAM:

from mobile_sam import SamPredictor, SamAutomaticMaskGenerator, sam_model_registry
model = sam_model_registry["vit_t"](checkpoint="mobile_sam.pt")
mask_generator = SamAutomaticMaskGenerator(model)
masks = mask_generator.generate(image)

Grounded-Segment-Anything:

from segment_anything import SamPredictor
from groundingdino.util.inference import load_model, load_image, predict
sam = SamPredictor(sam_checkpoint="sam_vit_h_4b8939.pth")
grounding_dino_model = load_model("groundingdino_swint_ogc.pth")
boxes, logits, phrases = predict(grounding_dino_model, image, text_prompt)

EfficientSAM: Leveraged Masked Image Pretraining for Efficient Segment Anything

Pros of EfficientSAM

  • Faster inference speed and lower computational requirements
  • Designed for efficient deployment on edge devices
  • Smaller model size, making it more suitable for resource-constrained environments

Cons of EfficientSAM

  • May have slightly lower accuracy compared to Grounded-Segment-Anything
  • Less versatile in terms of handling complex or diverse scenes
  • Limited integration with other AI models or tasks

Code Comparison

EfficientSAM:

from efficient_sam import EfficientSAM, EfficientSAMPredictor

model = EfficientSAM.from_pretrained("yformer/EfficientSAM-S")
predictor = EfficientSAMPredictor(model)
masks = predictor.predict(image)

Grounded-Segment-Anything:

from segment_anything import SamPredictor
from groundingdino.util.inference import load_model, load_image, predict

sam = SamPredictor(sam_checkpoint="sam_vit_h_4b8939.pth")
grounding_dino_model = load_model("groundingdino_swint_ogc.pth")
boxes, logits, phrases = predict(grounding_dino_model, image, text_prompt)
masks = sam.predict(boxes)

Both repositories aim to provide efficient segmentation capabilities, but EfficientSAM focuses more on speed and resource efficiency, while Grounded-Segment-Anything offers a more comprehensive approach with additional features like text-based object detection.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Grounded-Segment-Anything

YouTube Colab Open in Colab HuggingFace Space Replicate ModelScope Official Demo Huggingface Demo by Community Stable-Diffusion WebUI Jupyter Notebook Demo Static Badge Static Badge Static Badge

We plan to create a very interesting demo by combining Grounding DINO and Segment Anything which aims to detect and segment anything with text inputs! And we will continue to improve it and create more interesting demos based on this foundation. And we have already released an overall technical report about our project on arXiv, please check Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks for more details.

We are very willing to help everyone share and promote new projects based on Segment-Anything, Please check out here for more amazing demos and works in the community: Highlight Extension Projects. You can submit a new issue (with project tag) or a new pull request to add new project's links.

🍄 Why Building this Project?

The core idea behind this project is to combine the strengths of different models in order to build a very powerful pipeline for solving complex problems. And it's worth mentioning that this is a workflow for combining strong expert models, where all parts can be used separately or in combination, and can be replaced with any similar but different models (like replacing Grounding DINO with GLIP or other detectors / replacing Stable-Diffusion with ControlNet or GLIGEN/ Combining with ChatGPT).

🍇 Updates

Table of Contents

Preliminary Works

Here we provide some background knowledge that you may need to know before trying the demos.

TitleIntroDescriptionLinks
Segment-AnythingA strong foundation model aims to segment everything in an image, which needs prompts (as boxes/points/text) to generate masks[Github]
[Page]
[Demo]
Grounding DINOA strong zero-shot detector which is capable of to generate high quality boxes and labels with free-form text.[Github]
[Demo]
OSXA strong and efficient one-stage motion capture method to generate high quality 3D human mesh from monucular image. OSX also releases a large-scale upper-body dataset UBody for a more accurate reconstrution in the upper-body scene.[Github]
[Page]
[Video]
[Data]
Stable-DiffusionA super powerful open-source latent text-to-image diffusion model[Github]
[Page]
RAM++RAM++ is the next generation of RAM, which can recognize any category with high accuracy.[Github]
RAMRAM is an image tagging model, which can recognize any common category with high accuracy.[Github]
[Demo]
BLIPA wonderful language-vision model for image understanding.[GitHub]
Visual ChatGPTA wonderful tool that connects ChatGPT and a series of Visual Foundation Models to enable sending and receiving images during chatting.[Github]
[Demo]
Tag2TextAn efficient and controllable vision-language model which can simultaneously output superior image captioning and image tagging.[Github]
[Demo]
VoxelNeXtA clean, simple, and fully-sparse 3D object detector, which predicts objects directly upon sparse voxel features.[Github]

Highlighted Projects

Here we provide some impressive works you may find interesting:

TitleDescriptionLinks
Semantic-SAMA universal image segmentation model to enable segment and recognize anything at any desired granularity[Github]
[Demo]
SEEM: Segment Everything Everywhere All at OnceA powerful promptable segmentation model supports segmenting with various types of prompts (text, point, scribble, referring image, etc.) and any combination of prompts.[Github]
[Demo]
OpenSeeDA simple framework for open-vocabulary segmentation and detection which supports interactive segmentation with box input to generate mask[Github]
LLaVAVisual instruction tuning with GPT-4[Github]
[Page]
[Demo]
[Data]
[Model]
GenSAMRelaxing the instance-specific manual prompt requirement in SAM through training-free test-time adaptation[Github]
[Page]

We also list some awesome segment-anything extension projects here you may find interesting:

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 with Docker

Open one terminal:

make build-image
make run

That's it.

If you would like to allow visualization across docker container, open another terminal and type:

xhost +

Install without Docker

You should set the environment variable manually as follows if you want to build a local GPU environment for Grounded-SAM:

export AM_I_DOCKER=False
export BUILD_WITH_CUDA=True
export CUDA_HOME=/path/to/cuda-11.3/

Install Segment Anything:

python -m pip install -e segment_anything

Install Grounding DINO:

pip install --no-build-isolation -e GroundingDINO

Install diffusers:

pip install --upgrade diffusers[torch]

Install osx:

git submodule update --init --recursive
cd grounded-sam-osx && bash install.sh

Install RAM & Tag2Text:

git clone https://github.com/xinyu1205/recognize-anything.git
pip install -r ./recognize-anything/requirements.txt
pip install -e ./recognize-anything/

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 ipykernel

More details can be found in install segment anything and install GroundingDINO and install OSX

Grounded-SAM Playground

Let's start exploring our Grounding-SAM Playground and we will release more interesting demos in the future, stay tuned!

:open_book: Step-by-Step Notebook Demo

Here we list some notebook demo provided in this project:

:running_man: GroundingDINO: Detect Everything with Text Prompt

:grapes: [arXiv Paper]   :rose:[Try the Colab Demo]   :sunflower: [Try Huggingface Demo]   :mushroom: [Automated Dataset Annotation and Evaluation]

Here's the step-by-step tutorial on running GroundingDINO demo:

Step 1: Download the pretrained weights

cd Grounded-Segment-Anything

# download the pretrained groundingdino-swin-tiny model
wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth

Step 2: Running the demo

python grounding_dino_demo.py
Running with Python (same as demo but you can run it anywhere after installing GroundingDINO)
from groundingdino.util.inference import load_model, load_image, predict, annotate
import cv2

model = load_model("GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py", "./groundingdino_swint_ogc.pth")
IMAGE_PATH = "assets/demo1.jpg"
TEXT_PROMPT = "bear."
BOX_THRESHOLD = 0.35
TEXT_THRESHOLD = 0.25

image_source, image = load_image(IMAGE_PATH)

boxes, logits, phrases = predict(
    model=model,
    image=image,
    caption=TEXT_PROMPT,
    box_threshold=BOX_THRESHOLD,
    text_threshold=TEXT_THRESHOLD
)

annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
cv2.imwrite("annotated_image.jpg", annotated_frame)

Tips

  • If you want to detect multiple objects in one sentence with Grounding DINO, we suggest separating each name with . . An example: cat . dog . chair .

Step 3: Check the annotated image

The annotated image will be saved as ./annotated_image.jpg.

Text PromptDemo ImageAnnotated Image
Bear.
Horse. Clouds. Grasses. Sky. Hill

:running_man: Grounded-SAM: Detect and Segment Everything with Text Prompt

Here's the step-by-step tutorial on running Grounded-SAM demo:

Step 1: Download the pretrained weights

cd Grounded-Segment-Anything

wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth

We provide two versions of Grounded-SAM demo here:

Step 2: Running original grounded-sam demo

# depends on your device 
export CUDA_VISIBLE_DEVICES=0

python grounded_sam_demo.py \
  --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
  --grounded_checkpoint groundingdino_swint_ogc.pth \
  --sam_checkpoint sam_vit_h_4b8939.pth \
  --input_image assets/demo1.jpg \
  --output_dir "outputs" \
  --box_threshold 0.3 \
  --text_threshold 0.25 \
  --text_prompt "bear" \
  --device "cuda"

The annotated results will be saved in ./outputs as follows

Input ImageAnnotated ImageGenerated Mask

Step 3: Running grounded-sam demo with sam-hq

  • Download the demo image
wget https://github.com/IDEA-Research/detrex-storage/releases/download/grounded-sam-storage/sam_hq_demo_image.png
  • Download SAM-HQ checkpoint here

  • Running grounded-sam-hq demo as follows:

export CUDA_VISIBLE_DEVICES=0
python grounded_sam_demo.py \
  --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
  --grounded_checkpoint groundingdino_swint_ogc.pth \
  --sam_hq_checkpoint ./sam_hq_vit_h.pth \  # path to sam-hq checkpoint
  --use_sam_hq \  # set to use sam-hq model
  --input_image sam_hq_demo_image.png \
  --output_dir "outputs" \
  --box_threshold 0.3 \
  --text_threshold 0.25 \
  --text_prompt "chair." \
  --device "cuda"

The annotated results will be saved in ./outputs as follows

Input ImageSAM OutputSAM-HQ Output

Step 4: Running the updated grounded-sam demo (optional)

Note that this demo is almost same as the original demo, but with more elegant code.

python grounded_sam_simple_demo.py

The annotated results will be saved as ./groundingdino_annotated_image.jpg and ./grounded_sam_annotated_image.jpg

Text PromptInput ImageGroundingDINO Annotated ImageGrounded-SAM Annotated Image
The running dog
Horse. Clouds. Grasses. Sky. Hill

Step 5: Running the Sam model with multi-gpu

export CUDA_VISIBLE_DEVICES=0,1

python grounded_sam_multi_gpu_demo.py \
  --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
  --grounded_checkpoint groundingdino_swint_ogc.pth \
  --sam_checkpoint sam_vit_h_4b8939.pth \
  --input_path assets/car \
  --output_dir "outputs" \
  --box_threshold 0.3 \
  --text_threshold 0.25 \
  --text_prompt "car" \
  --device "cuda"

You will see that the model is loaded once per GPU

:skier: Grounded-SAM with Inpainting: Detect, Segment and Generate Everything with Text Prompt

Step 1: Download the pretrained weights

cd Grounded-Segment-Anything

wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth

Step 2: Running grounded-sam inpainting demo

CUDA_VISIBLE_DEVICES=0
python grounded_sam_inpainting_demo.py \
  --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
  --grounded_checkpoint groundingdino_swint_ogc.pth \
  --sam_checkpoint sam_vit_h_4b8939.pth \
  --input_image assets/inpaint_demo.jpg \
  --output_dir "outputs" \
  --box_threshold 0.3 \
  --text_threshold 0.25 \
  --det_prompt "bench" \
  --inpaint_prompt "A sofa, high quality, detailed" \
  --device "cuda"

The annotated and inpaint image will be saved in ./outputs

Step 3: Check the results

Input ImageDet PromptAnnotated ImageInpaint PromptInpaint Image
BenchA sofa, high quality, detailed

:golfing: Grounded-SAM and Inpaint Gradio APP

We support 6 tasks in the local Gradio APP:

  1. scribble: Segmentation is achieved through Segment Anything and mouse click interaction (you need to click on the object with the mouse, no need to specify the prompt).
  2. automask: Segment the entire image at once through Segment Anything (no need to specify a prompt).
  3. det: Realize detection through Grounding DINO and text interaction (text prompt needs to be specified).
  4. seg: Realize text interaction by combining Grounding DINO and Segment Anything to realize detection + segmentation (need to specify text prompt).
  5. inpainting: By combining Grounding DINO + Segment Anything + Stable Diffusion to achieve text exchange and replace the target object (need to specify text prompt and inpaint prompt) .
  6. automatic: By combining BLIP + Grounding DINO + Segment Anything to achieve non-interactive detection + segmentation (no need to specify prompt).
python gradio_app.py
  • The gradio_app visualization as follows:

:label: Grounded-SAM with RAM or Tag2Text for Automatic Labeling

The Recognize Anything Models are a series of open-source and strong fundamental image recognition models, including RAM++, RAM and Tag2text.

It is seamlessly linked to generate pseudo labels automatically as follows:

  1. Use RAM/Tag2Text to generate tags.
  2. Use Grounded-Segment-Anything to generate the boxes and masks.

Step 1: Init submodule and download the pretrained checkpoint

  • Init submodule:
cd Grounded-Segment-Anything
git submodule init
git submodule update
  • Download pretrained weights for GroundingDINO, SAM and RAM/Tag2Text:
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth


wget https://huggingface.co/spaces/xinyu1205/Tag2Text/resolve/main/ram_swin_large_14m.pth
wget https://huggingface.co/spaces/xinyu1205/Tag2Text/resolve/main/tag2text_swin_14m.pth

Step 2: Running the demo with RAM

export CUDA_VISIBLE_DEVICES=0
python automatic_label_ram_demo.py \
  --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
  --ram_checkpoint ram_swin_large_14m.pth \
  --grounded_checkpoint groundingdino_swint_ogc.pth \
  --sam_checkpoint sam_vit_h_4b8939.pth \
  --input_image assets/demo9.jpg \
  --output_dir "outputs" \
  --box_threshold 0.25 \
  --text_threshold 0.2 \
  --iou_threshold 0.5 \
  --device "cuda"

Step 2: Or Running the demo with Tag2Text

export CUDA_VISIBLE_DEVICES=0
python automatic_label_tag2text_demo.py \
  --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
  --tag2text_checkpoint tag2text_swin_14m.pth \
  --grounded_checkpoint groundingdino_swint_ogc.pth \
  --sam_checkpoint sam_vit_h_4b8939.pth \
  --input_image assets/demo9.jpg \
  --output_dir "outputs" \
  --box_threshold 0.25 \
  --text_threshold 0.2 \
  --iou_threshold 0.5 \
  --device "cuda"
  • RAM++ significantly improves the open-set capability of RAM, for RAM++ inference on unseen categoreis.
  • Tag2Text also provides powerful captioning capabilities, and the process with captions can refer to BLIP.
  • The pseudo labels and model prediction visualization will be saved in output_dir as follows (right figure):

:robot: Grounded-SAM with BLIP for Automatic Labeling

It is easy to generate pseudo labels automatically as follows:

  1. Use BLIP (or other caption models) to generate a caption.
  2. Extract tags from the caption. We use ChatGPT to handle the potential complicated sentences.
  3. Use Grounded-Segment-Anything to generate the boxes and masks.
  • Run Demo
export OPENAI_API_KEY=your_openai_key
export OPENAI_API_BASE=https://closeai.deno.dev/v1
export CUDA_VISIBLE_DEVICES=0
python automatic_label_demo.py \
  --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
  --grounded_checkpoint groundingdino_swint_ogc.pth \
  --sam_checkpoint sam_vit_h_4b8939.pth \
  --input_image assets/demo3.jpg \
  --output_dir "outputs" \
  --openai_key $OPENAI_API_KEY \
  --box_threshold 0.25 \
  --text_threshold 0.2 \
  --iou_threshold 0.5 \
  --device "cuda"
  • When you don't have a paid Account for ChatGPT is also possible to use NLTK instead. Just don't include the openai_key Parameter when starting the Demo.
    • The Script will automatically download the necessary NLTK Data.
  • The pseudo labels and model prediction visualization will be saved in output_dir as follows:

:open_mouth: Grounded-SAM with Whisper: Detect and Segment Anything with Audio

Detect and segment anything with speech!

Install Whisper

pip install -U openai-whisper

See the whisper official page if you have other questions for the installation.

Run Voice-to-Label Demo

Optional: Download the demo audio file

wget https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/demo_audio.mp3
export CUDA_VISIBLE_DEVICES=0
python grounded_sam_whisper_demo.py \
  --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
  --grounded_checkpoint groundingdino_swint_ogc.pth \
  --sam_checkpoint sam_vit_h_4b8939.pth \
  --input_image assets/demo4.jpg \
  --output_dir "outputs" \
  --box_threshold 0.3 \
  --text_threshold 0.25 \
  --speech_file "demo_audio.mp3" \
  --device "cuda"

Run Voice-to-inpaint Demo

You can enable chatgpt to help you automatically detect the object and inpainting order with --enable_chatgpt.

Or you can specify the object you want to inpaint [stored in args.det_speech_file] and the text you want to inpaint with [stored in args.inpaint_speech_file].

export OPENAI_API_KEY=your_openai_key
export OPENAI_API_BASE=https://closeai.deno.dev/v1
# Example: enable chatgpt
export CUDA_VISIBLE_DEVICES=0
python grounded_sam_whisper_inpainting_demo.py \
  --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
  --grounded_checkpoint groundingdino_swint_ogc.pth \
  --sam_checkpoint sam_vit_h_4b8939.pth \
  --input_image assets/inpaint_demo.jpg \
  --output_dir "outputs" \
  --box_threshold 0.3 \
  --text_threshold 0.25 \
  --prompt_speech_file assets/acoustics/prompt_speech_file.mp3 \
  --enable_chatgpt \
  --openai_key $OPENAI_API_KEY\
  --device "cuda"
# Example: without chatgpt
export CUDA_VISIBLE_DEVICES=0
python grounded_sam_whisper_inpainting_demo.py \
  --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
  --grounded_checkpoint groundingdino_swint_ogc.pth \
  --sam_checkpoint sam_vit_h_4b8939.pth \
  --input_image assets/inpaint_demo.jpg \
  --output_dir "outputs" \
  --box_threshold 0.3 \
  --text_threshold 0.25 \
  --det_speech_file "assets/acoustics/det_voice.mp3" \
  --inpaint_speech_file "assets/acoustics/inpaint_voice.mp3" \
  --device "cuda"

:speech_balloon: Grounded-SAM ChatBot Demo

https://user-images.githubusercontent.com/24236723/231955561-2ae4ec1a-c75f-4cc5-9b7b-517aa1432123.mp4

Following Visual ChatGPT, we add a ChatBot for our project. Currently, it supports:

  1. "Describe the image."
  2. "Detect the dog (and the cat) in the image."
  3. "Segment anything in the image."
  4. "Segment the dog (and the cat) in the image."
  5. "Help me label the image."
  6. "Replace the dog with a cat in the image."

To use the ChatBot:

  • Install whisper if you want to use audio as input.
  • Set the default model setting in the tool Grounded_dino_sam_inpainting.
  • Run Demo
export OPENAI_API_KEY=your_openai_key
export OPENAI_API_BASE=https://closeai.deno.dev/v1
export CUDA_VISIBLE_DEVICES=0
python chatbot.py 

:man_dancing: Run Grounded-Segment-Anything + OSX Demo


  • Download the checkpoint osx_l_wo_decoder.pth.tar from here for OSX:

  • Download the human model files and place it into grounded-sam-osx/utils/human_model_files following the instruction of OSX.

  • Run Demo

export CUDA_VISIBLE_DEVICES=0
python grounded_sam_osx_demo.py \
  --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
  --grounded_checkpoint groundingdino_swint_ogc.pth \
  --sam_checkpoint sam_vit_h_4b8939.pth \
  --osx_checkpoint osx_l_wo_decoder.pth.tar \
  --input_image assets/osx/grounded_sam_osx_demo.png \
  --output_dir "outputs" \
  --box_threshold 0.3 \
  --text_threshold 0.25 \
  --text_prompt "humans, chairs" \
  --device "cuda"
  • The model prediction visualization will be saved in output_dir as follows:
  • We also support promptable 3D whole-body mesh recovery. For example, you can track someone with a text prompt and estimate his 3D pose and shape :
space-1.jpg
A person with pink clothes
space-1.jpg
A man with a sunglasses

:man_dancing: Run Grounded-Segment-Anything + VISAM Demo

  • Download the checkpoint motrv2_dancetrack.pth from here for MOTRv2:

  • See the more thing if you have other questions for the installation.

  • Run Demo

export CUDA_VISIBLE_DEVICES=0
python grounded_sam_visam.py \
  --meta_arch motr \
  --dataset_file e2e_dance \
  --with_box_refine \
  --query_interaction_layer QIMv2 \
  --num_queries 10 \
  --det_db det_db_motrv2.json \
  --use_checkpoint \
  --mot_path your_data_path \
  --resume motrv2_dancetrack.pth \
  --sam_checkpoint sam_vit_h_4b8939.pth \
  --video_path DanceTrack/test/dancetrack0003 

||

:dancers: Interactive Editing

  • Release the interactive fashion-edit playground in here. Run in the notebook, just click for annotating points for further segmentation. Enjoy it!

  • Release human-face-edit branch here. We'll keep updating this branch with more interesting features. Here are some examples:

:camera: 3D-Box via Segment Anything

We extend the scope to 3D world by combining Segment Anything and VoxelNeXt. When we provide a prompt (e.g., a point / box), the result is not only 2D segmentation mask, but also 3D boxes. Please check voxelnext_3d_box for more details.

:cupid: Acknowledgements

Contributors

Our project wouldn't be possible without the contributions of these amazing people! Thank you all for making this project better.

Citation

If you find this project helpful for your research, please consider citing 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}
}

@article{liu2023grounding,
  title={Grounding dino: Marrying dino with grounded pre-training for open-set object detection},
  author={Liu, Shilong and Zeng, Zhaoyang and Ren, Tianhe and Li, Feng and Zhang, Hao and Yang, Jie and Li, Chunyuan and Yang, Jianwei and Su, Hang and Zhu, Jun and others},
  journal={arXiv preprint arXiv:2303.05499},
  year={2023}
}

@misc{ren2024grounded,
      title={Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks}, 
      author={Tianhe Ren and Shilong Liu and Ailing Zeng and Jing Lin and Kunchang Li and He Cao and Jiayu Chen and Xinyu Huang and Yukang Chen and Feng Yan and Zhaoyang Zeng and Hao Zhang and Feng Li and Jie Yang and Hongyang Li and Qing Jiang and Lei Zhang},
      year={2024},
      eprint={2401.14159},
      archivePrefix={arXiv},
      primaryClass={cs.CV}
}