> 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 Hosted API では利用できません。次で実行してください。 [専用デプロイメント](https://docs.roboflow.com/deployment/roboflow-cloud/dedicated-deployments) または [セルフホスト型 Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted).
{% endhint %}

## コード例

{% 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` Dedicated Deployment 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",
    json={
        "api_key": os.environ["ROBOFLOW_API_KEY"],
        "image": {"type": "base64", "value": image_base64},
        "text": ["犬", "人", "リュックサック"],
    },
)
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 %}

## 推論速度

レイテンシの測定条件： [Roboflow Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted) NVIDIA L4 1基、バッチサイズ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) サーバー用。
* あなたの [専用デプロイメント](https://docs.roboflow.com/deployment/roboflow-cloud/dedicated-deployments) プライベートエンドポイント用の URL。
  {% endhint %}

## Inference（セルフホスト型）で使用する

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

{% 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": ["りんご"],
        # オプションのしきい値。どちらもデフォルトは 0.5
        "box_threshold": 0.5,
        "text_threshold": 0.5,
    }
)

print(results)
```

置き換えてください `りんご` を、検出したいオブジェクトに置き換え、 `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 %}
