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

# SAM2

Metaの [Segment Anything Model 2](https://github.com/facebookresearch/sam2) による推論を [Serverless Cloud API](https://docs.roboflow.com/deployment/roboflow-cloud/serverless-api)。SAM2は、点とバウンディングボックスをプロンプトとして受け取る、プロンプト指定可能な視覚セグメンテーションモデルです。SAM2には2つのエンドポイントがあります:

* `/sam2/embed_image`、これは画像埋め込みを生成してキャッシュします
* `/sam2/segment_image`、これは与えられたプロンプトに対するインスタンスセグメンテーションマスクを返します

## SAM2 API

以下を使ってHTTPエンドポイント経由で直接SAM2を実行します `curl`、または [`inference-sdk`](https://docs.roboflow.com/reference/inference/inference-sdk) ラッパーを使用します。

{% tabs %}
{% tab title="HTTP（curl）" icon="webhook" %}
{% stepper %}
{% step %}

### APIキーを取得する

Roboflow アカウントを作成し、 [Roboflow API 設定ページ](https://app.roboflow.com/settings/api) でキーを見つけ、シェルで利用できるようにします。

```bash
export ROBOFLOW_API_KEY="your-key-here"
```

{% endstep %}

{% step %}

### モデルを実行する

次を呼び出します `/sam2/segment_image` エンドポイントを `curl`:

```bash
curl --location 'https://serverless.roboflow.com/sam2/segment_image' \
  --header 'Content-Type: application/json' \\
  --header "Authorization: Bearer $ROBOFLOW_API_KEY" \\
  --data '{
    "image": {"type": "url", "value": "https://media.roboflow.com/quickstart/traffic.jpg"},
    "prompts": {"prompts": [{"points": [{"x": 520, "y": 470, "positive": true}]}]},
    "sam2_version_id": "hiera_tiny"
  }'
```

{% endstep %}
{% endstepper %}
{% endtab %}

{% tab title="SDK（Python）" icon="python" %}
{% stepper %}
{% step %}

### APIキーを取得する

Roboflow アカウントを作成し、 [Roboflow API 設定ページ](https://app.roboflow.com/settings/api) でキーを見つけ、シェルで利用できるようにします。

```bash
export ROBOFLOW_API_KEY="your-key-here"
```

{% endstep %}

{% step %}

### 依存関係をインストールする

これらのパッケージはモデルを呼び出し、その結果を描画します:

```bash
pip install -U inference-sdk supervision opencv-python
```

{% endstep %}

{% step %}

### モデルを実行する

単一の正の点プロンプトでセグメンテーションエンドポイントを呼び出し、返されたポリゴンをsupervisionで検出結果に変換し、マスクを入力画像の上に描画した注釈付きPNGを保存します:

```python
import os
import cv2
import supervision as sv
from inference_sdk import InferenceHTTPClient, InferenceConfiguration

image = sv.load_image_from_url("https://media.roboflow.com/quickstart/traffic.jpg")
height, width = image.shape[:2]

client = InferenceHTTPClient(
    api_url="https://serverless.roboflow.com",
    api_key=os.environ["ROBOFLOW_API_KEY"],
).configure(InferenceConfiguration(api_key_transport="header"))

result = client.sam2_segment_image(
    inference_input=image,
    prompts=[
        {"points": [{"x": 520, "y": 470, "positive": True}]}
    ],
    sam2_version_id="hiera_tiny",
)

detections = sv.Detections.from_sam3(sam3_result=result, resolution_wh=(width, height))

annotated = sv.MaskAnnotator().annotate(image.copy(), detections)
cv2.imwrite("traffic_annotated.png", annotated)
```

`sv.Detections.from_sam3` は、SAM2とSAM3の両方が返すポリゴン予測を読み取るため、同じ呼び出しでどちらのモデルの出力もデコードできます。

<figure><img src="/files/9e0f6e45ba6196e67bcb2e2deb071e6b836aa982" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}
{% endtab %}
{% endtabs %}

## SAM2 推論速度

次で測定したレイテンシー [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>sam2</code></td><td>177.7</td></tr></tbody></table>

以下で測定: `segment_image` 上の `hiera_large` チェックポイント。SAM2は画像埋め込みをキャッシュするため、この図では各呼び出しで新しい画像を使い、エンコードとデコードの合計コストを反映しています。すでにエンコード済みの画像への再プロンプトは大幅に高速です。

{% hint style="info" %}
設定する `api_url` をデプロイ先に合わせます:

* `https://serverless.roboflow.com` サーバーレスクラウドAPI用。
* `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 %}

埋め込みのキャッシュやボックスプロンプトを含む追加の使用方法については、以下を参照してください [推論ドキュメント](https://docs.roboflow.com/deployment/self-hosted/self-hosted).

## セルフホストのInferenceでSAM2を実行する

SAM2は、以下を使って直接読み込むこともできます [`inference`](https://docs.roboflow.com/deployment/self-hosted/self-hosted) パッケージ、または自分で実行するGPUコンテナから提供できます。これは、画像を自分のハードウェア上に保持したい場合や、同じ画像に何度も再プロンプトする場合に適した方法です。

### Dockerで実行

のルートからSAM2イメージをビルドします [Inferenceリポジトリ](https://github.com/roboflow/inference):

```bash
docker build -f docker/dockerfiles/Dockerfile.sam2 -t sam2 .
```

次に、SAM2エンドポイントを公開するサーバーを起動します:

```bash
docker run -it --rm -v /tmp/cache/:/tmp/cache/ --gpus=all --net=host sam2
```

そのサーバーを `api_url` に指定すると（`http://localhost:9001`）、上記のコードサンプルは変更なしで動作します。

{% hint style="warning" %}
flash attention を使ったSAM2には [既知の問題があり](https://github.com/facebookresearch/sam2/issues/48) L4やA100を含む一部のGPUで発生します。そのスレッドの修正を適用するか、すでに対応済みの上記Dockerイメージを使用してください。
{% endhint %}

### Pythonでモデルを読み込む

```python
import os

os.environ["API_KEY"] = "YOUR_API_KEY"

from inference.core.entities.requests.sam2 import Sam2PromptSet
from inference.core.utils.postprocess import masks2poly
from inference.models.sam2 import SegmentAnything2

model = SegmentAnything2(model_id="sam2/hiera_large")

image_path = "./hand.png"

# 画像埋め込みを事前計算してキャッシュする
embedding, img_shape, image_id = model.embed_image(image_path)

# キャッシュ済み埋め込みを使ってセグメント化する
raw_masks, raw_low_res_masks = model.segment_image(image_path)
raw_masks = raw_masks >= model.predictor.mask_threshold
poly_masks = masks2poly(raw_masks)
```

埋め込みは自動的にキャッシュされるため、必要になると分かった時点で画像を埋め込み、その後は低コストで再プロンプトできます。

マスクを細かく調整するには、負の点（`"positive": False`）を送って領域を除外します:

```python
prompt = Sam2PromptSet(
    prompts=[{"points": [{"x": 250, "y": 800, "positive": False}]}]
)

refined_masks, refined_low_res_masks = model.segment_image(image_path, prompts=prompt)
refined_masks = refined_masks >= model.predictor.mask_threshold
```

利用可能 `model_id` の値: `sam2/hiera_tiny`, `sam2/hiera_small`, `sam2/hiera_b_plus`, `sam2/hiera_large`.

## WorkflowsでのSAM2ビデオトラッキング

この **SAM2 Video Tracker** ブロック（`roboflow_core/segment_anything_2_video@v1`)は、SAM2のストリーミング動画予測器をフレームごとに実行し、動画ごとの時系列メモリを保持してオブジェクトIDがフレーム間で維持されるようにします。上流の検出器からのバウンディングボックスを入力すると、各ボックスをマスクに変換してその後のフレームで追跡し、その `tracker_id` はSAM2がオブジェクトを追跡している限り安定したままです。マスクは、それらを生成した検出のクラス名、クラスID、信頼度を継承します。

* **状態を保持し、ローカルのみで動作します。** このブロックは各 `video_metadata.video_identifier`ごとに1つの追跡セッションを保持するため、多数のストリームを多重化できますが、セッションはプロセスメモリ内に存在します。 `WORKFLOWS_STEP_EXECUTION_MODE=local`、GPU、そして永続的なWebRTCセッションが必要です。個別のステートレスHTTPリクエストには適していません。
* **プロンプトのスケジューリング。** `prompt_mode` は、検出器のボックスをいつプロンプトとして消費するかを制御します: `first_frame` （デフォルト）はセッションごとに1回プロンプトし、その後は静かに追跡します; `every_n_frames` は毎 `prompt_interval` フレームごとに再シードし、シーンに入ってきたオブジェクトを拾います; `every_frame` は毎フレーム再シードし、安定したトラッカーIDを持つフレームごとの検出→マスク変換アダプタとして機能します。
* **モデルのバリエーション。** `model_id` はHieraバックボーンを選択します: `sam2video/tiny`, `sam2video/small` （デフォルト）, `sam2video/base-plus`, `sam2video/large`。このブロックはまた `sam3trackervideo`も受け付けます。これは、同じボックスプロンプト契約をより大きなバックボーンで使うSAM3の、視覚プロンプト付きトラッカーです。より高い計算コストの代わりに、長い動画や混雑したシーンでIDをよりよく保持します。最高品質の階層として扱い、 `sam2video` サイズを速度階層として扱ってください。

```python
from inference_sdk import InferenceHTTPClient
from inference_sdk.webrtc import StreamConfig, VideoFileSource

WORKFLOW = {
    "version": "1.0",
    "inputs": [{"type": "InferenceImage", "name": "image"}],
    "steps": [
        {
            "type": "roboflow_core/roboflow_object_detection_model@v2",
            "name": "detector",
            "images": "$inputs.image",
            "model_id": "yolov8n-640",
        },
        {
            "type": "roboflow_core/segment_anything_2_video@v1",
            "name": "tracker",
            "images": "$inputs.image",
            "boxes": "$steps.detector.predictions",
            "prompt_mode": "every_n_frames",
            "prompt_interval": 30,
        },
    ],
    "outputs": [
        {
            "type": "JsonField",
            "name": "predictions",
            "selector": "$steps.tracker.predictions",
        }
    ],
}

client = InferenceHTTPClient(
    api_url="http://localhost:9001",
    api_key="YOUR_API_KEY",
)

session = client.webrtc.stream(
    source=VideoFileSource("path/to/video.mp4"),
    workflow=WORKFLOW,
    config=StreamConfig(data_output=["predictions"]),
)

@session.on_data("predictions")
def handle_predictions(predictions, metadata):
    print(predictions)

session.run()
```

テキストプロンプトからのオープンボキャブラリ動画トラッキングで、上流の検出器がない場合は、以下のSAM3 Video Trackerブロックを参照してください [SAM3ページ](/models/ja/supported-models/sam3.md).

### Workflowsの実行モード

画像ワークフローで使用する場合、SAM2は次の2つのモードのいずれかで実行されます:

* **ローカル実行**: モデルはあなたのInferenceサーバー上で実行されます（GPUを強く推奨）。
* **リモート実行**：モデルは、次を介してリモートInferenceサーバー上でHTTP経由で呼び出されます： `sam2_segment_image()` クライアントメソッド。

## 関連項目

* [SAM3](/models/ja/supported-models/sam3.md) - テキストプロンプトから概念のすべてのインスタンスをセグメント化します。
* [Segment Anything（SAM）](/models/ja/supported-models/sam.md) - 元の単一オブジェクトモデル。
