> 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는 오픈 보캐브러리 객체 검출기입니다. 이미지를 하나와 텍스트 클래스 목록을 전달하면, 모델은 학습 없이도 일치하는 영역에 대한 바운딩 박스를 반환합니다.

{% 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` 전용 배포 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": ["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/cbd05bdb2fac4fcdd5f3f26855cb31d1ab5c4330" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

## 추론 속도

다음을 사용해 측정한 지연 시간 [Roboflow Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted) 1x 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>

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

{% 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": ["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 %}
