> 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) 当社の [サーバーレスホスト型 API](https://docs.roboflow.com/deployment/roboflow-cloud/serverless-api). SAM2は、点とバウンディングボックスをプロンプトとして受け取る、プロンプト指定可能な視覚セグメンテーションモデルです。SAM2のエンドポイントは2つあります:

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

## コード例

以下を使って、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' \
  --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 %}

## 推論速度

レイテンシの測定条件： [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>sam2</code></td><td>177.7</td></tr></tbody></table>

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

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

* `https://serverless.roboflow.com` Serverless Hosted 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は、 [`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 Video Tracker** ブロック（`roboflow_core/segment_anything_2_video@v1`は SAM2 のストリーミング動画予測器をフレームごとに実行し、動画ごとの時間的メモリを保持することで、フレーム間でオブジェクトIDを維持します。上流の検出器からのバウンディングボックスを入力すると、各ボックスをマスクに変換し、以降のフレームで追跡して、次のようなセグメンテーション予測を出力します: `tracker_id` SAM2 がオブジェクトを追跡している限り安定したままです。マスクには、それらを生成した検出のクラス名、クラスID、信頼度が引き継がれます。

* **ステートフルで、ローカル限定です。** このブロックは、1つの追跡セッションをそれぞれの `video_metadata.video_identifier`ごとに保持するため、多数のストリームを多重化できますが、セッションはプロセスメモリ内に存在します。必要条件は `WORKFLOWS_STEP_EXECUTION_MODE=local`、GPU、および永続的な WebRTC セッションです。個別のステートレスなHTTPリクエストには適していません。
* **プロンプトのスケジューリング。** `prompt_mode` は、検出器のボックスをいつプロンプトとして消費するかを制御します: `first_frame` （デフォルト）セッションごとに1回プロンプトし、その後は静かに追跡します; `every_n_frames` 〜ごとに再シードします `prompt_interval` フレームごとに、シーンに入ってきたオブジェクトを拾います; `every_frame` 毎フレーム再シードし、安定した tracker\_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) - 元の単一オブジェクトモデル。
