> 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/ko/supported-models/grounding-dino.md).

# Grounding DINO

Grounding DINO 텍스트 프롬프트 기반 객체 감지 API를 전용 배포 또는 자체 호스팅 추론에서 실행

Grounding DINO는 개방형 어휘 객체 탐지기입니다. 이미지와 텍스트 클래스 목록을 전달하면, 모델은 추가 학습 없이 일치하는 영역의 경계 상자를 반환합니다.

{% hint style="info" %}
Grounding DINO는 Serverless Cloud API에서 사용할 수 없습니다. 다음에서 실행하세요: [전용 배포](https://docs.roboflow.com/deployment/roboflow-cloud/dedicated-deployments) 또는 [자체 호스팅 추론](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": ["개", "사람", "배낭"],
    },
)
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="https://2225311784-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fcmo9mhfIjYrvFFy1U7dk%2Fuploads%2Fgit-blob-185612dfa2f7c1a662cfcc081f10057397f7e4fd%2Fgrounding-dino-detection.webp?alt=media" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

## Grounding DINO 추론 속도

다음을 사용하여 측정한 지연 시간 [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>

두 개의 텍스트 프롬프트로 측정했습니다.

{% 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 실행하기

또한 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 %}
