# GroundingDINO

Erkenne beliebige Objekte mithilfe von Textbeschreibungen mit GroundingDINO.

{% hint style="success" %}
Alle Beispiele können auf GPU-Servern ausgeführt werden, die über [CLORE.AI Marketplace](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 Marketplace](https://clore.ai/marketplace) Marktplatz ausgeführt werden.
{% endhint %}

## Mieten auf CLORE.AI

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

### Zugriff auf Ihren Server

* Verbindungsdetails finden Sie in **Meine Bestellungen**
* Webschnittstellen: Verwenden Sie die HTTP-Port-URL
* SSH: `ssh -p <port> root@<proxy-address>`

## Was ist GroundingDINO?

GroundingDINO von IDEA-Research ermöglicht:

* Zero-Shot-Objekterkennung mit Textprompten
* Erkenne beliebige Objekte ohne Training
* Hochpräzise Lokalisierung mit Begrenzungsrahmen
* Kombinierbar mit SAM für automatische Segmentierung

## 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 12GB | RTX 4080 16GB | RTX 4090 24GB |
| VRAM       | 6GB           | 12GB          | 16GB          |
| CPU        | 4 Kerne       | 8 Kerne       | 16 Kerne      |
| RAM        | 16GB          | 32GB          | 64GB          |
| Speicher   | 20GB SSD      | 50GB NVMe     | 100GB NVMe    |
| Internet   | 100 Mbps      | 500 Mbps      | 1 Gbps        |

## Schnelle Bereitstellung auf CLORE.AI

**Docker-Image:**

```
pytorch/pytorch:2.5.1-cuda12.4-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
```

## Zugriff auf Ihren Dienst

Nach der Bereitstellung finden Sie Ihre `http_pub` URL in **Meine Bestellungen**:

1. Gehen Sie zur **Meine Bestellungen** Seite
2. Klicken Sie auf Ihre Bestellung
3. Finden Sie die `http_pub` URL (z. B., `abc123.clorecloud.net`)

Verwenden Sie `https://IHRE_HTTP_PUB_URL` anstelle von `localhost` in den Beispielen unten.

## 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 Sie erstellen können

### Automatisierte Beschriftung

* Automatische Annotierung von Datensätzen für ML-Training
* Erzeuge Begrenzungsrahmen aus Beschreibungen
* Beschleunige Datenbeschriftungspipelines

### Visuelle Suche

* Finde bestimmte Objekte in Bilddatenbanken
* Systeme zur Inhaltsmoderation
* Produkterkennung im Einzelhandel

### Robotik & Automation

* Objektlokalisierung für Roboterarme
* Inventarverwaltungssysteme
* Qualitätskontrollinspektion

### Kreative Anwendungen

* Automatisches Zuschneiden von Motiven aus Fotos
* Generiere Objektmasken mit SAM
* Inhaltsbewusstes Bildbearbeiten

### Analytik

* Zähle Objekte in Bildern
* Verfolge Inventar anhand von Fotos
* 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)

Kombiniere Erkennung mit Segmentierung:

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

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

# Lade SAM
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")

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

# Segmentieren mit SAM
sam_predictor.set_image(image_source)

# Konvertiere Boxen in SAM-Format
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}: Found {len(boxes)} objects")
```

## Eigene 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 umrechnen
    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

# Erkenne Autos und Personen
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"Found {len(boxes)} objects: {', '.join(phrases)}"

demo = gr.Interface(
    fn=detect_objects,
    inputs=[
        gr.Image(type="pil", label="Eingabebild"),
        gr.Textbox(label="Objects to Detect", 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="Detection Result"),
        gr.Textbox(label="Summary")
    ],
    title="GroundingDINO - Open-Set Object Detection",
    description="Detect any object by describing it in text. Running on CLORE.AI GPU servers."
)

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

## Leistung

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

## 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 = "red car . person wearing hat . wooden chair"

# Schlechtes Prompt-Format
TEXT_PROMPT = "red car, person wearing hat, wooden chair"
```

### Kein Speicher mehr

**Problem:** CUDA OOM bei großen Bildern

**Lösungen:**

```python

# Verkleinere große Bilder vor der Erkennung
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:** Erkennung dauert zu lange

**Lösungen:**

* Verwende kleinere Eingabebilder
* Verarbeite mehrere Bilder im Batch
* Verwende FP16-Inferenz
* Miete schnellere GPU (RTX 4090, A100)

### Falsch positive Ergebnisse

**Problem:** Falsche Objekte werden erkannt

**Lösungen:**

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

```python

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

## Fehlerbehebung

### Objekte werden nicht erkannt

* Verwende spezifischere Textbeschreibungen
* Probiere unterschiedliche Formulierungen
* Senk die Konfidenzschwelle

### Begrenzungsrahmen sind falsch

* Sei im Textprompt spezifischer
* Verwende "." um mehrere Objekte zu trennen
* Bildqualität prüfen

{% hint style="danger" %}
**Kein Speicher mehr**
{% endhint %}

* Reduziere die Bildauflösung
* Verarbeite Bilder einzeln
* Verwende eine kleinere Modellvariante

### Langsame Inferenz

* Verwende TensorRT zur Beschleunigung
* Batche Bilder ähnlicher Größe
* Aktiviere FP16-Inferenz

## Kostenabschätzung

Typische CLORE.AI-Marktplatztarife (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           |

*Preise variieren je nach Anbieter und Nachfrage. Prüfen Sie* [*CLORE.AI Marketplace*](https://clore.ai/marketplace) *auf aktuelle Preise.*

**Geld sparen:**

* Verwenden Sie **Spot** Markt für flexible Workloads (oft 30–50% günstiger)
* Bezahlen mit **CLORE** Token
* Preise bei verschiedenen Anbietern vergleichen

## Nächste Schritte

* [SAM2](https://docs.clore.ai/guides/guides_v2-de/vision-modelle/sam2-video) - Segmentieren erkannter Objekte
* [Florence-2](https://docs.clore.ai/guides/guides_v2-de/vision-modelle/florence2) - Mehr Vision-Aufgaben
* [YOLO](https://docs.clore.ai/guides/guides_v2-de/computer-vision/yolov8-detection) - Schnellere Erkennung für bekannte Klassen
