> 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

SAM2 を HTTP エンドポイントから直接実行するには、 `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' \
  --data '{
    "api_key": "'"$ROBOFLOW_API_KEY"'",
    "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

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"],
)

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) を1x 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) サーバー。
* プライベートエンドポイントの [専用デプロイメント](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 のストリーミング動画予測器をフレームごとに実行し、動画ごとの時間的メモリを保持してオブジェクトの同一性をフレーム間で維持します。上流の検出器からのバウンディングボックスを渡すと、各ボックスをマスクに変換し、後続フレームで追跡して、次のセグメンテーション予測を出力します。その `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 の視覚プロンプト付きトラッカーです。より大きなバックボーンを使い、同じボックスプロンプト契約に対応しています。長い動画や混雑したシーンでも同一性をよりよく維持しますが、計算コストは高くなります。最高品質の階層として扱い、 `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 ページの SAM3 Video Tracker ブロックを参照してください](/models/ja/supported-models/sam3.md).

### Workflows の実行モード

画像 Workflow で使用する場合、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) - 元の単一オブジェクトモデル。
