> For the complete documentation index, see [llms.txt](https://docs.roboflow.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.roboflow.com/models/ja/supported-models/grounding-dino.md).

# Grounding DINO

Grounding DINO はオープン語彙の物体検出器です。画像とテキストクラスの一覧を渡すと、学習なしで一致する領域のバウンディングボックスをモデルが返します。

{% hint style="info" %}
Grounding DINO は Serverless Cloud API では利用できません。これを実行するには [Dedicated Deployment](https://docs.roboflow.com/deployment/roboflow-cloud/dedicated-deployments) または [self-hosted Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted).
{% endhint %}

## Grounding DINO API

{% stepper %}
{% step %}

### APIキーを取得する

Roboflow アカウントを作成し、 [Roboflow API 設定ページ](https://app.roboflow.com/settings/api) でキーを見つけ、シェルで利用できるようにします。

```bash
export ROBOFLOW_API_KEY="your-key-here"
```

{% endstep %}

{% step %}

### 依存関係をインストールする

これらのパッケージは API を呼び出し、その結果を描画します:

```bash
pip install -U requests supervision opencv-python
```

{% endstep %}

{% step %}

### モデルを実行する

設定する `URL` 専用デプロイURLまたはローカル推論サーバーに対して。

```python
import base64
import os
import cv2
import numpy as np
import requests
import supervision as sv

URL = "https://your-deployment.roboflow.cloud"
image = sv.load_image_from_url("https://media.roboflow.com/notebooks/examples/dog.jpeg")
_, buffer = cv2.imencode(".jpg", image)
image_base64 = base64.b64encode(buffer).decode("utf-8")

response = requests.post(
    f"{URL}/grounding_dino/infer",
    headers={"Authorization": f"Bearer {os.environ['ROBOFLOW_API_KEY']}"},
    json={
        "image": {"type": "base64", "value": image_base64},
        "text": ["dog", "person", "backpack"],
    },
)
preds = response.json()["predictions"]

xyxys = [
    [p["x"] - p["width"] / 2, p["y"] - p["height"] / 2,
     p["x"] + p["width"] / 2, p["y"] + p["height"] / 2]
    for p in preds
]
detections = sv.Detections(
    xyxy=np.array(xyxys, dtype=float),
    class_id=np.array([p.get("class_id", 0) for p in preds]),
    confidence=np.array([p["confidence"] for p in preds], dtype=float),
    data={"class_name": np.array([p["class"] for p in preds])},
)
labels = [f"{p['class']} {p['confidence']:.2f}" for p in preds]
annotated = sv.BoxAnnotator().annotate(image.copy(), detections)
annotated = sv.LabelAnnotator().annotate(annotated, detections, labels=labels)
cv2.imwrite("dog_annotated.png", annotated)
```

<figure><img src="/files/2df72b9e5087b763b9cbe7b9b71e4beb8f615ec9" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

## Grounding DINO 推論速度

次で測定したレイテンシー [Roboflow Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted) 1台のNVIDIA L4、バッチサイズ1、ウォームアップ後の平均で測定。

<table data-search="false"><thead><tr><th>モデル</th><th>レイテンシー（ms）</th></tr></thead><tbody><tr><td><code>grounding-dino</code></td><td>165.4</td></tr></tbody></table>

2つのテキストプロンプトで計測。

{% hint style="info" %}
設定する `URL` をデプロイ先に合わせます:

* `http://localhost:9001` ローカルの [Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted) サーバー用。
* あなたの [Dedicated Deployment](https://docs.roboflow.com/deployment/roboflow-cloud/dedicated-deployments) プライベートエンドポイント用のURL。
  {% endhint %}

## セルフホストの Inference で Grounding DINO を実行する

また、Grounding DINO を [`inference`](https://docs.roboflow.com/deployment/self-hosted/self-hosted) パッケージを使って、HTTP の往復を完全に省略しつつ、自分の Python プロセスに直接読み込むこともできます。

{% stepper %}
{% step %}

### パッケージをインストールする

```bash
pip install "inference[grounding-dino]"
```

{% endstep %}

{% step %}

### モデルを実行する

```python
from inference.models.grounding_dino import GroundingDINO

model = GroundingDINO(api_key="YOUR_API_KEY")

results = model.infer(
    {
        "image": {
            "type": "url",
            "value": "https://media.roboflow.com/fruit.png",
        },
        "text": ["apple"],
        # 省略可能な閾値。どちらもデフォルトは 0.5
        "box_threshold": 0.5,
        "text_threshold": 0.5,
    }
)

print(results)
```

置き換えてください `apple` を検出したい物体に置き換え、 `box_threshold` と `text_threshold` を用途に合わせて調整してください。しきい値の説明については [Grounding DINO README](https://github.com/IDEA-Research/GroundingDINO?tab=readme-ov-file#star-explanationstips-for-grounding-dino-inputs-and-outputs) をご覧ください。
{% endstep %}
{% endstepper %}

{% hint style="info" %}
Grounding DINO は一般的な物体（車、人、犬）に最も効果的です。狭い、きめ細かなカテゴリには弱いため、プロンプトの文言を試してください。よくある方法は、Grounding DINO でデータを自動ラベル付けし、その結果でより小さく高速な検出器を学習させることです。
{% endhint %}
