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

## OWLv2 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 %}

### モデルを実行する

以下のサンプルでは、入力画像上の 1 つのサンプルボックスをプロンプトとして使用し、同じ画像内の一致する物体を検出します。実際には、通常は別の参照画像を渡します。次を設定してください `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}/owlv2/infer",
    headers={"Authorization": f"Bearer {os.environ['ROBOFLOW_API_KEY']}"},
    json={
        "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 %}

## OWLv2 の推論速度

次で測定したレイテンシー [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>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) サーバー用。
* あなたの [Dedicated Deployment](https://docs.roboflow.com/deployment/roboflow-cloud/dedicated-deployments) プライベートエンドポイント用のURL。
  {% endhint %}

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

## セルフホスト型 Inference で OWLv2 を実行する

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