> 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/owlv2.md).

# OwlV2

OwlV2 は Google のオープンボキャブラリー物体検出器です。参照画像上で 1 つ以上のサンプル境界ボックスを指定すると、OwlV2 はトレーニングなしでターゲット画像内の類似した物体を検出します。

{% hint style="info" %}
OwlV2 は 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 %}

### モデルを実行する

以下のサンプルでは、入力画像上の 1 つのサンプル बॉックスをプロンプトとして使用し、同じ画像内の一致する物体を検出します。実際には通常、別の参照画像を渡します。を設定してください `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}/owlv2/infer",
    json={
        "api_key": os.environ["ROBOFLOW_API_KEY"],
        "image": {"type": "base64", "value": image_base64},
        "training_data": [{
            "image": {"type": "base64", "value": image_base64},
            "boxes": [{"x": 360, "y": 800, "w": 500, "h": 500, "cls": "dog"}],
        }],
        "confidence": 0.99,
    },
)
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/4be439c0f66a096cdba9d97e9fa7246705980656" 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>owlv2</code></td><td>541.2</td></tr></tbody></table>

以下で測定: `owlv2-large-patch14-ensemble` 、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 %}

OwlV2 の信頼度は通常非常に高く（0.99 以上）、 `confidence` パラメータをそれに応じて調整してください。

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

OwlV2 は、 [`inference`](https://docs.roboflow.com/deployment/self-hosted/self-hosted) パッケージで直接読み込めます。Inference における実装は、 *視覚的な* 例から物体を検出します。1 つ以上のサンプル物体を बॉックスで囲むと、モデルが似たものを見つけます。

{% stepper %}
{% step %}

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

```bash
pip install "inference[transformers]"
```

以下を使用してください： `inference-gpu[transformers]` GPU マシン上で。
{% endstep %}

{% step %}

### モデルを実行する

```python
import base64
import io

from PIL import Image

from inference.core.entities.requests.owlv2 import OwlV2InferenceRequest
from inference.models.owlv2.owlv2 import OwlV2

image = {"type": "url", "value": "https://media.roboflow.com/inference/seawithdock.jpeg"}

request = OwlV2InferenceRequest(
    image=image,
    training_data=[
        {
            "image": image,
            "boxes": [{"x": 223, "y": 306, "w": 40, "h": 226, "cls": "post"}],
        }
    ],
    visualize_predictions=True,
    confidence=0.9999,
)

response = OwlV2().infer_from_request(request)

visualization = Image.open(io.BytesIO(response.visualization))
visualization.save("owlv2_visualization.jpg")
```

置き換えてください `training_data` 一致させたいサンプル物体と、独自の入力画像 URL を指定します。注釈付きの結果は次に書き出されます `owlv2_visualization.jpg`.
{% endstep %}
{% endstepper %}
