> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-de/computer-vision-modelle/groundingdino.md).

# GroundingDINO

Erkenne jedes Objekt mithilfe von Textbeschreibungen mit GroundingDINO

Erkenne beliebige Objekte mithilfe von Textbeschreibungen mit GroundingDINO.

{% hint style="success" %}
Alle Beispiele können auf GPU-Servern ausgeführt werden, die gemietet wurden über [CLORE.AI-Marktplatz](https://clore.ai/marketplace).
{% endhint %}

{% hint style="info" %}
Alle Beispiele in diesem Leitfaden können auf GPU-Servern ausgeführt werden, die über [CLORE.AI-Marktplatz](https://clore.ai/marketplace) Marktplatz gemietet werden.
{% endhint %}

## Mieten auf CLORE.AI

1. Besuchen [CLORE.AI-Marktplatz](https://clore.ai/marketplace)
2. Filtern nach GPU-Typ, VRAM und Preis
3. Wähle **On-Demand** (Festpreis) oder **Spot** (Gebotspreis)
4. Konfiguriere deine Bestellung:
   * Docker-Image auswählen
   * Ports festlegen (TCP für SSH, HTTP für Web-UIs)
   * Bei Bedarf Umgebungsvariablen hinzufügen
   * Startbefehl eingeben
5. Zahlung auswählen: **CLORE**, **BTC**, oder **USDT/USDC**
6. Bestellung erstellen und auf die Bereitstellung warten

### Greife auf deinen Server zu

* Verbindungsdetails finden in **Meine Bestellungen**
* Web-Oberflächen: Verwende die HTTP-Port-URL
* SSH: `ssh -p <port> root@<proxy-address>`

## Was ist GroundingDINO?

GroundingDINO von IDEA-Research ermöglicht:

* Zero-Shot-Objekterkennung mit Text-Prompts
* Beliebige Objekte ohne Training erkennen
* Hochpräzise Lokalisierung von Bounding Boxes
* Mit SAM für automatische Segmentierung kombinieren

## Ressourcen

* **GitHub:** [IDEA-Research/GroundingDINO](https://github.com/IDEA-Research/GroundingDINO)
* **Paper:** [GroundingDINO-Paper](https://arxiv.org/abs/2303.05499)
* **HuggingFace:** [IDEA-Research/grounding-dino](https://huggingface.co/IDEA-Research/grounding-dino-base)
* **Demo:** [HuggingFace Space](https://huggingface.co/spaces/IDEA-Research/Grounding_DINO_Demo)

## Empfohlene Hardware

| Komponente | Minimum        | Empfohlen      | Optimal       |
| ---------- | -------------- | -------------- | ------------- |
| GPU        | RTX 3060 12 GB | RTX 4080 16 GB | RTX 4090 24GB |
| VRAM       | 6 GB           | 12 GB          | 16 GB         |
| CPU        | 4 Kerne        | 8 Kerne        | 16 Kerne      |
| RAM        | 16 GB          | 32 GB          | 64 GB         |
| Speicher   | 20GB SSD       | 50 GB NVMe     | 100 GB NVMe   |
| Internet   | 100 Mbit/s     | 500 Mbit/s     | 1 Gbit/s      |

## Schnellbereitstellung auf CLORE.AI

**Docker-Image:**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
```

**Ports:**

```
22/tcp
7860/http
```

**Befehl:**

```bash
cd /workspace && \
git clone https://github.com/IDEA-Research/GroundingDINO.git && \
cd GroundingDINO && \
pip install -e . && \
python demo/gradio_demo.py
```

## Auf deinen Dienst zugreifen

Nach der Bereitstellung findest du deine `http_pub` URL in **Meine Bestellungen**:

1. Gehe zu **Meine Bestellungen** Seite
2. Klicke auf deine Bestellung
3. Finde die `http_pub` URL (z. B. `abc123.clorecloud.net`)

Verwende `https://YOUR_HTTP_PUB_URL` anstelle von `localhost` in den folgenden Beispielen.

## Installation

```bash
git clone https://github.com/IDEA-Research/GroundingDINO.git
cd GroundingDINO
pip install -e .

# Gewichte herunterladen
mkdir weights
cd weights
wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
```

## Was du erstellen kannst

### Automatisches Labeling

* Datensätze für ML-Training automatisch annotieren
* Bounding Boxes aus Beschreibungen generieren
* Daten-Labeling-Pipelines beschleunigen

### Visuelle Suche

* Bestimmte Objekte in Bilddatenbanken finden
* Systeme zur Inhaltsmoderation
* Produkterkennung im Einzelhandel

### Robotik & Automatisierung

* Objektlokalisierung für Roboterarme
* Bestandsverwaltungssysteme
* Qualitätskontrolle und Inspektion

### Kreative Anwendungen

* Motiv automatisch aus Fotos zuschneiden
* Objektmasken mit SAM generieren
* Kontextabhängige Bildbearbeitung

### Analytik

* Objekte in Bildern zählen
* Bestände aus Fotos verfolgen
* Wildtierüberwachung

## Grundlegende Verwendung

```python
from groundingdino.util.inference import load_model, load_image, predict, annotate
import cv2

# Modell laden
model = load_model(
    "groundingdino/config/GroundingDINO_SwinT_OGC.py",
    "weights/groundingdino_swint_ogc.pth"
)

# Bild laden
image_source, image = load_image("input.jpg")

# Objekte erkennen
TEXT_PROMPT = "cat . dog . person"
BOX_THRESHOLD = 0.35
TEXT_THRESHOLD = 0.25

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

# Bild annotieren
annotated_frame = annotate(
    image_source=image_source,
    boxes=boxes,
    logits=logits,
    phrases=phrases
)

cv2.imwrite("output.jpg", annotated_frame)
```

## GroundingDINO + SAM (Grounded-SAM)

Erkennung mit Segmentierung kombinieren:

```python
import torch
import numpy as np
from groundingdino.util.inference import load_model, load_image, predict
from segment_anything import sam_model_registry, SamPredictor

# GroundingDINO laden
dino_model = load_model(
    "groundingdino/config/GroundingDINO_SwinT_OGC.py",
    "weights/groundingdino_swint_ogc.pth"
)

# SAM laden
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to(device="cuda")
sam_predictor = SamPredictor(sam)

# Bild laden
image_source, image = load_image("input.jpg")

# Mit GroundingDINO erkennen
boxes, logits, phrases = predict(
    model=dino_model,
    image=image,
    caption="person . car",
    box_threshold=0.35,
    text_threshold=0.25
)

# Mit SAM segmentieren
sam_predictor.set_image(image_source)

# Bounding Boxes ins SAM-Format umwandeln
H, W = image_source.shape[:2]
boxes_xyxy = boxes * torch.tensor([W, H, W, H])

masks = []
for box in boxes_xyxy:
    mask, _, _ = sam_predictor.predict(
        box=box.numpy(),
        multimask_output=False
    )
    masks.append(mask)
```

## Batch-Verarbeitung

```python
import os
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"
)

input_dir = "./images"
output_dir = "./detected"
os.makedirs(output_dir, exist_ok=True)

TEXT_PROMPT = "product . price tag . barcode"

for filename in os.listdir(input_dir):
    if not filename.endswith(('.jpg', '.png')):
        continue

    image_path = os.path.join(input_dir, filename)
    image_source, image = load_image(image_path)

    boxes, logits, phrases = predict(
        model=model,
        image=image,
        caption=TEXT_PROMPT,
        box_threshold=0.3,
        text_threshold=0.25
    )

    annotated = annotate(image_source, boxes, logits, phrases)
    cv2.imwrite(os.path.join(output_dir, filename), annotated)

    print(f"{filename}: {len(boxes)} Objekte gefunden")
```

## Benutzerdefinierte Erkennungspipeline

```python
from groundingdino.util.inference import load_model, load_image, predict
import json

model = load_model(
    "groundingdino/config/GroundingDINO_SwinT_OGC.py",
    "weights/groundingdino_swint_ogc.pth"
)

def detect_and_export(image_path, prompt, output_json):
    image_source, image = load_image(image_path)
    H, W = image_source.shape[:2]

    boxes, logits, phrases = predict(
        model=model,
        image=image,
        caption=prompt,
        box_threshold=0.35,
        text_threshold=0.25
    )

    # In absolute Koordinaten umwandeln
    detections = []
    for box, logit, phrase in zip(boxes, logits, phrases):
        x1, y1, x2, y2 = box * torch.tensor([W, H, W, H])
        detections.append({
            "label": phrase,
            "confidence": float(logit),
            "bbox": {
                "x1": int(x1),
                "y1": int(y1),
                "x2": int(x2),
                "y2": int(y2)
            }
        })

    with open(output_json, "w") as f:
        json.dump(detections, f, indent=2)

    return detections

# Autos und Personen erkennen
results = detect_and_export(
    "street.jpg",
    "car . person . bicycle . traffic light",
    "detections.json"
)
```

## Gradio-Oberfläche

```python
import gradio as gr
import cv2
from groundingdino.util.inference import load_model, load_image, predict, annotate
import tempfile
import numpy as np

model = load_model(
    "groundingdino/config/GroundingDINO_SwinT_OGC.py",
    "weights/groundingdino_swint_ogc.pth"
)

def detect_objects(image, text_prompt, box_threshold, text_threshold):
    # Temporäres Bild speichern
    with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
        cv2.imwrite(f.name, cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR))
        image_source, img = load_image(f.name)

    boxes, logits, phrases = predict(
        model=model,
        image=img,
        caption=text_prompt,
        box_threshold=box_threshold,
        text_threshold=text_threshold
    )

    annotated = annotate(image_source, boxes, logits, phrases)
    annotated_rgb = cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB)

    return annotated_rgb, f"{len(boxes)} Objekte gefunden: {', '.join(phrases)}"

demo = gr.Interface(
    fn=detect_objects,
    inputs=[
        gr.Image(type="pil", label="Eingabebild"),
        gr.Textbox(label="Zu erkennende Objekte", value="person . car . dog", placeholder="object1 . object2 . object3"),
        gr.Slider(0.1, 0.9, value=0.35, label="Box-Threshold"),
        gr.Slider(0.1, 0.9, value=0.25, label="Text-Threshold")
    ],
    outputs=[
        gr.Image(label="Erkennungsergebnis"),
        gr.Textbox(label="Zusammenfassung")
    ],
    title="GroundingDINO - Open-Set-Objekterkennung",
    description="Erkenne beliebige Objekte, indem du sie in Text beschreibst. Läuft auf CLORE.AI GPU-Servern."
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## Leistung

| Aufgabe           | Auflösung | GPU      | Geschwindigkeit |
| ----------------- | --------- | -------- | --------------- |
| Einzelbild        | 800x600   | RTX 3090 | 120ms           |
| Einzelbild        | 800x600   | RTX 4090 | 80ms            |
| Einzelbild        | 1920x1080 | RTX 4090 | 150ms           |
| Batch (10 Bilder) | 800x600   | RTX 4090 | 600 ms          |

## Häufige Probleme & Lösungen

### Geringe Erkennungsgenauigkeit

**Problem:** Objekte werden nicht erkannt

**Lösungen:**

* Niedriger `box_threshold` auf 0.2-0.3
* Niedriger `text_threshold` auf 0.15-0.2
* Verwende spezifischere Objektbeschreibungen
* Trenne Objekte mit " . " und nicht mit Kommas

```python

# Gutes Prompt-Format
TEXT_PROMPT = "rotes Auto . Person mit Hut . Holzstuhl"

# Schlechtes Prompt-Format
TEXT_PROMPT = "rotes Auto, Person mit Hut, Holzstuhl"
```

### Speicher erschöpft

**Problem:** CUDA-OMM bei großen Bildern

**Lösungen:**

```python

# Große Bilder vor der Erkennung skalieren
from PIL import Image

def resize_if_needed(image_path, max_size=1280):
    img = Image.open(image_path)
    if max(img.size) > max_size:
        ratio = max_size / max(img.size)
        new_size = (int(img.width * ratio), int(img.height * ratio))
        img = img.resize(new_size, Image.LANCZOS)
        img.save(image_path)
```

### Langsame Inferenz

**Problem:** Die Erkennung dauert zu lange

**Lösungen:**

* Verwende kleinere Eingabebilder
* Verarbeite mehrere Bilder stapelweise
* Verwende FP16-Inferenz
* Schnellere GPU mieten (RTX 4090, A100)

### Falschpositive

**Problem:** Falsche Objekte werden erkannt

**Lösungen:**

* Erhöhen Sie `box_threshold` auf 0.4-0.5
* Sei in den Prompts spezifischer
* Verwende negative Prompts (Ergebnisse nach der Erkennung filtern)

```python

# Erkennungen mit niedriger Konfidenz filtern
filtered = [(b, l, p) for b, l, p in zip(boxes, logits, phrases) if l > 0.5]
```

## Fehlerbehebung

### Objekte nicht erkannt

* Verwende spezifischere Textbeschreibungen
* Probiere verschiedene Formulierungen aus
* Konfidenzschwellenwert senken

### Bounding Boxes falsch

* Sei in der Text-Prompt genauer
* Verwende "." zur Trennung mehrerer Objekte
* Bildqualität prüfen

{% hint style="danger" %}
**Speicher voll**
{% endhint %}

* Bildauflösung reduzieren
* Bilder einzeln verarbeiten
* Kleinere Modellvariante verwenden

### Langsame Inferenz

* TensorRT zur Beschleunigung verwenden
* Bilder ähnlicher Größe stapelweise verarbeiten
* FP16-Inferenz aktivieren

## Kostenschätzung

Übliche CLORE.AI-Marktplatzpreise (Stand 2024):

| GPU       | Stundensatz | Tagessatz | 4-Stunden-Sitzung |
| --------- | ----------- | --------- | ----------------- |
| RTX 3060  | \~$0.03     | \~$0.70   | \~$0.12           |
| RTX 3090  | \~$0.06     | \~$1.50   | \~$0.25           |
| RTX 4090  | \~$0.10     | \~$2.30   | \~$0.40           |
| A100 40GB | \~$0.17     | \~$4.00   | \~$0.70           |
| A100 80GB | \~$0.25     | \~$6.00   | \~$1.00           |

*Die Preise variieren je nach Anbieter und Nachfrage. Prüfen Sie* [*CLORE.AI-Marktplatz*](https://clore.ai/marketplace) *für aktuelle Preise.*

**Geld sparen:**

* Nutzen Sie den **Spot** Markt für unterbrechbare Arbeit — etwa ein Drittel der Server bietet Spot-Preise unter dem On-Demand-Preis (Median ca. 13 % Rabatt), der Rest ist gleichauf
* Bezahlen Sie mit **CLORE** Tokens
* Vergleichen Sie Preise zwischen verschiedenen Anbietern

## Nächste Schritte

* [SAM2](/guides/guides_v2-de/computer-vision-modelle/sam2-video.md) - Erkannte Objekte segmentieren
* [Florence-2](/guides/guides_v2-de/computer-vision-modelle/florence2.md) - Mehr Vision-Aufgaben
* [YOLO](/guides/guides_v2-de/computer-vision/yolov8-detection.md) - Schnellere Erkennung für bekannte Klassen


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-de/computer-vision-modelle/groundingdino.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
