Overview of Grounding DINO
main(image, text) pair). It is highly capable in zero-shot scenarios, achieving 52.5 AP on COCO without COCO training data.repository·main·Indexed 27 days ago
https://github.com/idea-research/groundingdinoGrounding DINO is a high-performance, open-set object detection model that uses natural language prompts to identify arbitrary objects in images. It features zero-shot capabilities, marrying DINO with grounded pre-training to achieve high AP on COCO without specific training data. The repository provides tools for CLI and Python API inference, including utilities for loading models, processing images, and annotating results. It also supports integration with Hugging Face Transformers and workflows for image inpainting using Stable Diffusion.
(image, text) pair). It is highly capable in zero-shot scenarios, achieving 52.5 AP on COCO without COCO training data.Grounding DINO requires an (image, text) pair.
900 object boxes.box_threshold to select boxes whose highest similarity scores exceed the threshold.text_threshold to extract predicted labels from words with high similarity..) for better performance.You can interact with Grounding DINO through several official and community-provided channels:
transformers library. Refer to the Huggingface documentation for implementation details.Follow these steps to install Grounding DINO.
Important: CUDA Setup
If you have a CUDA environment, you must set the CUDA_HOME environment variable. If not set, the package will compile in CPU-only mode, which may lead to NameError: name '_C' is not defined errors. To fix this, ensure CUDA_HOME points to your CUDA toolkit installation (e.g., /usr/local/cuda).
Installation Steps:
# 1. Clone
git clone https://github.com/IDEA-Research/GroundingDINO.git
# 2. Change directory
cd GroundingDINO/
# 3. Install dependencies
pip install -e .
# 4. Download weights
mkdir weights
cd weights
wget -q https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
cd ..Combine Grounding DINO detections with a StableDiffusionInpaintPipeline to edit images.
Note: The mask must be white (255) for the area to be inpainted and black (0) for the area to be kept.
# image_source, image_mask are PIL images
image_source_for_inpaint = image_source.resize((512, 512))
image_mask_for_inpaint = image_mask.resize((512, 512))
prompt = "a cute dinosaur"
# image and mask_image should be PIL images.
image_inpainting = pipe(prompt=prompt, image=image_source_for_inpaint, mask_image=image_mask_for_inpaint).images[0]
# Resize back to original size
image_inpainting = image_inpainting.resize((image_source.size[0], image_source.size[1]))To use the image editing workflow combining Grounding DINO with Stable Diffusion, you must install the diffusers, transformers, accelerate, scipy, and safetensors libraries.
! pip install diffusers transformers accelerate scipy safetensorsRun the demo/test_ap_on_coco.py script to evaluate the model's zero-shot performance on the COCO dataset. Expected result is approximately 48.5.
CUDA_VISIBLE_DEVICES=0 \
python demo/test_ap_on_coco.py \
-c groundingdino/config/GroundingDINO_SwinT_OGC.py \
-p weights/groundingdino_swint_ogc.pth \
--anno_path /path/to/annoataions/ie/instances_val2017.json \
--image_dir /path/to/imagedir/ie/val2017Import the inference utilities to integrate Grounding DINO into your Python applications.
Workflow:
load_model: Load the model using a config file and weights.load_image: Load the image and return both the source and the processed image.predict: Perform inference with box_threshold and text_threshold.annotate: Generate an annotated image frame.cv2 to save the result.from groundingdino.util.inference import load_model, load_image, predict, annotate
import cv2
model = load_model("groundingdino/config/GroundingDINO_SwinT_OGC.py", "weights/groundingdino_swint_ogc.pth")
IMAGE_PATH = "weights/dog-3.jpeg"
TEXT_PROMPT = "chair . person . dog ."
BOX_TRESHOLD = 0.35
TEXT_TRESHOLD = 0.25
image_source, image = load_image(IMAGE_PATH)
boxes, logits, phrases = predict(
model=model,
image=image,
caption=TEXT_PROMPT,
box_threshold=BOX_TRESHOLD,
text_threshold=TEXT_TRESHOLD
)
annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
cv2.imwrite("annotated_image.jpg", annotated_frame)The repository provides two main model variants:
You can perform object detection by loading a model with a specific configuration and weight file, then using the predict function with a text prompt. The predict function returns bounding boxes, confidence logits, and the associated text phrases. Use annotate to draw the detected boxes and labels onto the original image source.
from groundingdino.util.inference import load_model, load_image, predict, annotate
import cv2
# Load model with config and weights
model = load_model("groundingdino/config/GroundingDINO_SwinT_OGC.py", "../04-06-segment-anything/weights/groundingdino_swint_ogc.pth")
IMAGE_PATH = ".asset/cat_dog.jpeg"
TEXT_PROMPT = "chair . person . dog ."
BOX_TRESHOLD = 0.35
TEXT_TRESHOLD = 0.25
# Load and preprocess image
image_source, image = load_image(IMAGE_PATH)
# Run inference
boxes, logits, phrases = predict(
model=model,
image=image,
caption=TEXT_PROMPT,
box_threshold=BOX_TRESHOLD,
text_threshold=TEXT_TRESHOLD
)
# Annotate and save result
annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
cv2.imwrite("annotated_image.jpg", annotated_frame)Use the demo/inference_on_a_image.py script to perform object detection from the command line. You can specify the GPU via CUDA_VISIBLE_DEVICES and use the --cpu-only flag to run on CPU.
Arguments:
-c: Path to the configuration file.-p: Path to the model weights.-i: Path to the input image.-o: Directory to save the output.-t: Text prompt (phrases to detect).--token_spans: (Optional) Specifies start and end positions of phrases for precise detection. Format: [[[start, end], [start, end]], ...].# Basic detection
CUDA_VISIBLE_DEVICES={GPU ID} python demo/inference_on_a_image.py \
-c groundingdino/config/GroundingDINO_SwinT_OGC.py \
-p weights/groundingdino_swint_ogc.pth \
-i image_you_want_to_detect.jpg \
-o "dir you want to save the output" \
-t "chair"
# Detection with specific token spans
CUDA_VISIBLE_DEVICES={GPU ID} python demo/inference_on_a_image.py \
-c groundingdino/config/GroundingDINO_SwinT_OGC.py \
-p ./groundingdino_swint_ogc.pth \
-i .asset/cat_dog.jpeg \
-o logs/1111 \
-t "There is a cat and a dog in the image ." \
--token_spans "[[[9, 10], [11, 14]], [[19, 20], [21, 24]]]"To prepare for image inpainting, convert the normalized bounding boxes returned by Grounding DINO into a binary mask. The generate_masks_with_grounding function creates a mask where the detected object areas are set to 255 (white) and the rest is 0 (black).
def generate_masks_with_grounding(image_source, boxes):
h, w, _ = image_source.shape
boxes_unnorm = boxes * torch.Tensor([w, h, w, h])
boxes_xyxy = box_convert(boxes=boxes_unnorm, in_fmt="cxcywh", out_fmt="xyxy").numpy()
mask = np.zeros_like(image_source)
for box in boxes_xyxy:
x0, y0, x1, y1 = box
mask[int(y0):int(y1), int(x0):int(x1), :] = 255
return mask
image_mask = generate_masks_with_grounding(image_source, boxes)