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

# SAM3

Metaの [Segment Anything Model 3](https://github.com/facebookresearch/sam3) による推論を [Serverless Cloud API](https://docs.roboflow.com/deployment/roboflow-cloud/serverless-api)。SAM3のエンドポイントは2種類あります：

{% hint style="info" %}
RoboflowでSAM3モデルをトレーニングするには、有料 [プラン](https://docs.roboflow.com/platform/billing-and-plans/plans) に含まれる [従量課金](https://docs.roboflow.com/platform/billing-and-plans/credits)。そこから、SAM3アーキテクチャの「Request Feature」ボタンでアクセスをリクエストし、この機能を使用できます [トレーニングフロー](/models/ja/readme.md).

ファインチューニングしたSAM3モデルは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)。ホストされている `sam3` のこのページ上のエンドポイントは影響を受けません。
{% endhint %}

* [プロンプト可能な概念セグメンテーション](#sam3-concept-segmentation-pcs) (**PCS**）は、画像内の概念のすべてのインスタンスをセグメントします。概念はテキストプロンプト、例示ボックス、またはその両方で指定します。
* [プロンプト可能な視覚セグメンテーション](#sam3-visual-segmentation-pvs) (**PVS**）は、SAM2のように、点またはボックスからリクエストごとに1つのオブジェクトを対話的にセグメントします。

エンドポイントを選ぶにはこの表を使ってください：

<table data-search="false"><thead><tr><th>入力が</th><th>目的が</th><th>使用する</th></tr></thead><tbody><tr><td>テキストによる説明（例: "person"）</td><td>一致するすべてのインスタンスのマスク</td><td><code>/sam3/concept_segment</code></td></tr><tr><td>1つの例示オブジェクトを囲むボックス</td><td>類似するすべてのインスタンスのマスク</td><td><code>/sam3/concept_segment</code></td></tr><tr><td>オブジェクトを含める／除外するためのテキストと例示ボックス</td><td>一致するすべてのインスタンスのマスク</td><td><code>/sam3/concept_segment</code></td></tr><tr><td>特定の1つのオブジェクト上のクリックまたはボックス</td><td>そのオブジェクトのみのマスク</td><td><code>/sam3/visual_segment</code></td></tr></tbody></table>

送信する [APIキー](https://app.roboflow.com/settings/api) を `Authorization: Bearer` ヘッダーを各リクエストに含めてください。従来の `api_key` クエリパラメータも引き続き機能しますが、推奨されません。

## SAM3概念セグメンテーション（PCS）

`POST https://serverless.roboflow.com/sam3/concept_segment`

の各エントリは `prompts` で1つの概念を表します。レスポンスには各プロンプトごとに1つの `prompt_results` エントリが含まれ、それぞれに見つかったすべてのインスタンスが入ります。リクエストは最大16個のプロンプトを受け付けます。

### テキストプロンプト

```python
import os
import requests

payload = {
    "image": {"type": "url", "value": "https://media.roboflow.com/inference/people-walking.jpg"},
    "prompts": [
        {"type": "text", "text": "人"},
        {"type": "text", "text": "バックパック"},
    ],
    "output_prob_thresh": 0.5,
    "format": "polygon",  # または "rle"
}

response = requests.post(
    "https://serverless.roboflow.com/sam3/concept_segment",
    headers={"Authorization": f"Bearer {os.environ['ROBOFLOW_API_KEY']}"},
    json=payload,
)
for prompt_result in response.json()["prompt_results"]:
    print(prompt_result["echo"], len(prompt_result["predictions"]), "インスタンス")
```

画像はインラインでも次の形式で送信できます： `{"type": "base64", "value": "<BASE64_IMAGE>"}`.

### 例示ボックスプロンプト

テキストの代わりに、例示を使ってプロンプトできます。つまり、1つの例示オブジェクトを囲むボックスです。モデルは、ボックスで囲んだオブジェクトだけでなく、その例に一致するすべてのインスタンスを見つけます。

```python
payload = {
    "image": {"type": "url", "value": "https://media.roboflow.com/inference/people-walking.jpg"},
    "prompts": [
        {
            "type": "visual",
            "boxes": [{"x": 1409, "y": 705, "width": 112, "height": 183}],
            "box_labels": [1],
        }
    ],
    "output_prob_thresh": 0.5,
    "format": "polygon",
}
```

ボックスは絶対ピクセル座標を使用します。次の2つの形式が受け付けられます：

* `{"x": ..., "y": ..., "width": ..., "height": ...}` ここで `x`, `y` は左上隅です
* `{"x0": ..., "y0": ..., "x1": ..., "y1": ...}` 明示的な角指定用

`box_labels` は、次の場合に必要です： `boxes` が設定されている場合。ボックスごとに1つのエントリが必要です： `1` は正の例示（このようなオブジェクトを見つける）を示し、 `0` は負の例示（このようなオブジェクトを除外する）を示します。

### テキストと例示を組み合わせたプロンプト

1つのプロンプトにテキストと例示ボックスの両方を含められます。これは、視覚的な例でテキスト概念を絞り込んだり、負の例示で似たものを除外したりするのに便利です：

```python
payload = {
    "image": {"type": "url", "value": "https://media.roboflow.com/inference/people-walking.jpg"},
    "prompts": [
        {
            "type": "visual",
            "text": "人",
            "boxes": [
                {"x": 1409, "y": 705, "width": 112, "height": 183},
                {"x": 1216, "y": 496, "width": 124, "height": 184},
            ],
            "box_labels": [1, 0],
        }
    ],
    "output_prob_thresh": 0.5,
    "format": "polygon",
}
```

ここでは、モデルは最初の（正の）例示に一致する人をセグメントし、2つ目の（負の）例示に似たインスタンスは抑制します。

## SAM3視覚セグメンテーション（PVS）

`POST https://serverless.roboflow.com/sam3/visual_segment`

PVSは、クリックまたはボックスで指定した特定の1つのオブジェクトをセグメントします。対話的な人手介在型のマスク調整に使ってください。概念のすべてのインスタンスが必要な場合はPCSを使ってください。

```python
import os
import requests

payload = {
    "image": {"type": "url", "value": "https://media.roboflow.com/inference/people-walking.jpg"},
    "prompts": {
        "prompts": [
            {
                "points": [{"x": 1465, "y": 796, "positive": True}],
                "box": {"x": 1465, "y": 796, "width": 112, "height": 183},
            }
        ]
    },
    "multimask_output": False,
    "format": "json",
}

response = requests.post(
    "https://serverless.roboflow.com/sam3/visual_segment",
    headers={"Authorization": f"Bearer {os.environ['ROBOFLOW_API_KEY']}"},
    json=payload,
)
prediction = response.json()["predictions"][0]
print(prediction["confidence"], len(prediction["masks"]), "ポリゴン")
```

プロンプトには次を含められます： `points`、 `box`またはその両方：

* `points` は絶対ピクセル座標です。 `"positive": true` はクリックした領域を含み、 `false` はそれを除外します。マスクをさらに調整するには、追加のポイントを加えてください。
* `box` は中央基準の座標を使用します： `x`, `y` はボックスの中心です。PCSのボックスが左上基準なのとは異なります。

レスポンスには、そのプロンプトに対する信頼度が最も高い1つのマスクが含まれます。 `multimask_output` モデルが内部で生成するマスク候補の数を制御します（trueのときは3つ）。ただし、レスポンスには常に最良の候補が選ばれます。

{% hint style="warning" %}
1回のリクエストにつき1つのプロンプトを送信してください。現在、1つのPVSリクエストで複数のプロンプトを送っても予測は1つしか返りません。
{% endhint %}

OpenCVを使った対話デモについては、こちらを参照してください： [GitHub Gist](https://gist.github.com/Erol444/4cbc33c6ac52d83c63f6f9d86ca8a7a4)。これはこの動画で使用されました：

{% embed url="<https://www.youtube.com/watch?v=01xrBzqHZ6c>" %}

## SAM3の推論速度

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

単一のテキストプロンプトによる概念セグメンテーションで測定。

## SAM3 APIエンドポイント

## SAM3 PCS (promptable concept segmentation)

> \*\*Concept Segmentation (Text Prompts)\*\*\
> \
> Allows you to segment objects using text prompts.\
> \
> \*\*Image Input\*\*: The \`image\` field accepts either:\
> \- \`{"type": "url", "value": "\<IMAGE\_URL>"}\` - A publicly accessible image URL\
> \- \`{"type": "base64", "value": "\<BASE64\_DATA>"}\` - Base64 encoded image data\
> \
> &#x20;\*\*Prompts\*\*: Each prompt in the \`prompts\` array should have \`type: "text"\` and a \`text\` field with the object description.

```json
{"openapi":"3.1.0","info":{"title":"Roboflow SAM3 API","version":"0.64.4"},"servers":[{"url":"https://serverless.roboflow.com"}],"paths":{"/sam3/concept_segment":{"post":{"summary":"SAM3 PCS (promptable concept segmentation)","description":"**Concept Segmentation (Text Prompts)**\n\nAllows you to segment objects using text prompts.\n\n**Image Input**: The `image` field accepts either:\n- `{\"type\": \"url\", \"value\": \"<IMAGE_URL>\"}` - A publicly accessible image URL\n- `{\"type\": \"base64\", \"value\": \"<BASE64_DATA>\"}` - Base64 encoded image data\n\n **Prompts**: Each prompt in the `prompts` array should have `type: \"text\"` and a `text` field with the object description.","operationId":"sam3_segment_image_sam3_concept_segment_post","parameters":[{"name":"api_key","in":"query","required":true,"schema":{"type":"string","title":"API Key"},"description":"Your Roboflow API Key. Get one at https://app.roboflow.com/settings/api"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Sam3SegmentationRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Sam3SegmentationResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"Sam3SegmentationRequest":{"properties":{"image":{"$ref":"#/components/schemas/InferenceRequestImage","description":"The image to be segmented."},"prompts":{"items":{"$ref":"#/components/schemas/Sam3Prompt"},"type":"array","minItems":1,"title":"Prompts","description":"List of prompts (text and/or visual)"},"format":{"type":"string","title":"Format","description":"One of 'polygon', 'rle'","default":"polygon"},"image_id":{"type":"string","title":"Image Id","description":"Optional ID for caching embeddings."},"output_prob_thresh":{"type":"number","title":"Output Prob Thresh","description":"Score threshold for outputs.","default":0.5},"model_id":{"type":"string","title":"Model Id","description":"The model ID of SAM3. Use 'sam3/sam3_final' to target the generic base model.","default":"sam3/sam3_final"},"nms_iou_threshold":{"type":"number","title":"Nms Iou Threshold","description":"IoU threshold for cross-prompt NMS. If not set, NMS is disabled. Must be in [0.0, 1.0] when set."}},"type":"object","required":["image","prompts"],"title":"Sam3SegmentationRequest"},"InferenceRequestImage":{"properties":{"type":{"type":"string","title":"Type","description":"The type of image data provided, one of `url`, `base64`"},"value":{"type":"string","title":"Value","description":"Image data corresponding to the image type, if type = 'url' then value is a string containing the url of an image, else if type = 'base64' then value is a string containing base64 encoded image data."}},"type":"object","required":["type"],"title":"InferenceRequestImage","description":"Image data for inference request.\n\nAttributes:\n    type (str): The type of image data provided, one of 'url', 'base64', or 'numpy'.\n    value (Optional[Any]): Image data corresponding to the image type."},"Sam3Prompt":{"properties":{"type":{"type":"string","title":"Type","description":"Hint: `text` or `visual`"},"text":{"type":"string","title":"Text","description":"Text prompt describing the object to segment"},"output_prob_thresh":{"type":"number","title":"Output Prob Thresh","description":"Score threshold for this prompt's outputs. Overrides request-level threshold if set."},"boxes":{"items":{"anyOf":[{"$ref":"#/components/schemas/Box"},{"$ref":"#/components/schemas/BoxXYXY"}]},"type":"array","title":"Boxes","description":"Absolute pixel boxes as either XYWH or XYXY entries"},"box_labels":{"items":{"anyOf":[{"type":"integer"},{"type":"boolean"}]},"type":"array","title":"Box Labels","description":"List of 0/1 or booleans for boxes"}},"type":"object","required":["type"],"title":"Sam3Prompt","description":"Unified prompt that can contain text and/or geometry. Absolute pixel coordinates are used for boxes."},"Sam3SegmentationResponse":{"properties":{"prompt_results":{"items":{"$ref":"#/components/schemas/Sam3PromptResult"},"type":"array","title":"Prompt Results","description":"Results for each prompt in the request"},"time":{"type":"number","title":"Time","description":"The time in seconds it took to produce the segmentation including preprocessing"}},"type":"object","required":["prompt_results","time"],"title":"Sam3SegmentationResponse"},"Sam3PromptResult":{"properties":{"prompt_index":{"type":"integer","title":"Prompt Index","description":"Index of the prompt this result corresponds to"},"echo":{"$ref":"#/components/schemas/Sam3PromptEcho","description":"Echo of the original prompt for reference"},"predictions":{"items":{"$ref":"#/components/schemas/Sam3SegmentationPrediction"},"type":"array","title":"Predictions","description":"Segmentation predictions for this prompt"}},"type":"object","required":["prompt_index","predictions"],"title":"Sam3PromptResult"},"Sam3PromptEcho":{"properties":{"prompt_index":{"type":"integer","title":"Prompt Index"},"type":{"type":"string","title":"Type","description":"The prompt type (`text` or `visual`)"},"text":{"type":"string","title":"Text","description":"The text prompt if type is `text`"},"num_boxes":{"type":"integer","title":"Num Boxes","description":"Number of bounding boxes in the prompt"}},"type":"object","title":"Sam3PromptEcho"},"Sam3SegmentationPrediction":{"properties":{"format":{"type":"string","title":"Format","description":"The format of the mask data, either `polygon` or `rle`"},"confidence":{"type":"number","title":"Confidence","description":"Confidence score for this prediction"},"masks":{"items":{"items":{"items":{"type":"number"},"type":"array","minItems":2,"maxItems":2},"type":"array"},"type":"array","title":"Masks","description":"Array of polygons, each polygon is an array of [x, y] coordinate points"}},"type":"object","required":["format","confidence","masks"],"title":"Sam3SegmentationPrediction"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}
```

## SAM3 PVS (promptable visual segmentation)

> \*\*Interactive Segmentation (SAM 2 Style)\*\*\
> \
> SAM 3 also supports interactive segmentation using points and boxes.\
> \
> \*\*Image Input\*\*: The \`image\` field accepts either:\
> \- \`{"type": "url", "value": "\<IMAGE\_URL>"}\` - A publicly accessible image URL\
> \- \`{"type": "base64", "value": "\<BASE64\_DATA>"}\` - Base64 encoded image data\
> \
> \> \*\*Note\*\*: NumPy arrays are NOT supported on the serverless API. Use URL or base64 encoding only.\
> \
> \*\*Prompts\*\*: Support point-based prompts with positive/negative clicks for interactive segmentation.

```json
{"openapi":"3.1.0","info":{"title":"Roboflow SAM3 API","version":"0.64.4"},"servers":[{"url":"https://serverless.roboflow.com"}],"paths":{"/sam3/visual_segment":{"post":{"summary":"SAM3 PVS (promptable visual segmentation)","description":"**Interactive Segmentation (SAM 2 Style)**\n\nSAM 3 also supports interactive segmentation using points and boxes.\n\n**Image Input**: The `image` field accepts either:\n- `{\"type\": \"url\", \"value\": \"<IMAGE_URL>\"}` - A publicly accessible image URL\n- `{\"type\": \"base64\", \"value\": \"<BASE64_DATA>\"}` - Base64 encoded image data\n\n> **Note**: NumPy arrays are NOT supported on the serverless API. Use URL or base64 encoding only.\n\n**Prompts**: Support point-based prompts with positive/negative clicks for interactive segmentation.","operationId":"sam3_visual_segment_sam3_visual_segment_post","parameters":[{"name":"api_key","in":"query","required":true,"schema":{"type":"string","title":"API Key"},"description":"Your Roboflow API Key. Get one at https://app.roboflow.com/settings/api"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/Sam2SegmentationRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Sam2SegmentationResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"Sam2SegmentationRequest":{"properties":{"image":{"$ref":"#/components/schemas/InferenceRequestImage","description":"The image to be segmented."},"image_id":{"type":"string","title":"Image Id","description":"The ID of the image to be segmented used to retrieve cached embeddings. If an embedding is cached, it will be used instead of generating a new embedding. If no embedding is cached, a new embedding will be generated and cached."},"prompts":{"$ref":"#/components/schemas/Sam2PromptSet","description":"A list of prompts for masks to predict. Each prompt can include a bounding box and / or a set of postive or negative points."},"format":{"type":"string","title":"Format","description":"The format of the response. Must be one of 'json', 'rle', or 'binary'. If binary, masks are returned as binary numpy arrays. If json, masks are converted to polygons. If rle, masks are converted to RLE format.","default":"json"},"sam2_version_id":{"type":"string","title":"Sam2 Version Id","description":"The version ID of SAM to be used for this request. Must be one of hiera_tiny, hiera_small, hiera_large, hiera_b_plus","default":"hiera_large"},"multimask_output":{"type":"boolean","title":"Multimask Output","description":"If true, the model will return three masks. For ambiguous input prompts (such as a single click), this will often produce better masks than a single prediction.","default":true},"save_logits_to_cache":{"type":"boolean","title":"Save Logits To Cache","description":"If True, saves the low-resolution logits to the cache for potential future use.","default":false},"load_logits_from_cache":{"type":"boolean","title":"Load Logits From Cache","description":"If True, attempts to load previously cached low-resolution logits for the given image and prompt set.","default":false}},"type":"object","required":["image"],"title":"Sam2SegmentationRequest","description":"SAM2 visual segmentation request."},"InferenceRequestImage":{"properties":{"type":{"type":"string","title":"Type","description":"The type of image data provided, one of `url`, `base64`"},"value":{"type":"string","title":"Value","description":"Image data corresponding to the image type, if type = 'url' then value is a string containing the url of an image, else if type = 'base64' then value is a string containing base64 encoded image data."}},"type":"object","required":["type"],"title":"InferenceRequestImage","description":"Image data for inference request.\n\nAttributes:\n    type (str): The type of image data provided, one of 'url', 'base64', or 'numpy'.\n    value (Optional[Any]): Image data corresponding to the image type."},"Sam2SegmentationResponse":{"properties":{"prompt_results":{"items":{"$ref":"#/components/schemas/Sam2PromptResult"},"type":"array","title":"Prompt Results","description":"Results for each prompt in the request"},"time":{"type":"number","title":"Time","description":"The time in seconds it took to produce the segmentation including preprocessing"}},"type":"object","required":["prompt_results","time"],"title":"Sam2SegmentationResponse"},"Sam2PromptResult":{"properties":{"prompt_index":{"type":"integer","title":"Prompt Index","description":"Index of the prompt this result corresponds to"},"predictions":{"items":{"$ref":"#/components/schemas/Sam2SegmentationPrediction"},"type":"array","title":"Predictions","description":"Segmentation predictions for this prompt"}},"type":"object","required":["prompt_index","predictions"],"title":"Sam2PromptResult"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}
```

## self-hosted InferenceでSAM3を実行

SAM3は、自前のハードウェアでも実行できます。インプロセスで次のものを使って読み込むか、 [`inference`](https://docs.roboflow.com/deployment/self-hosted/self-hosted) パッケージを使うか、GPUコンテナから提供できます。

### Dockerで実行

```bash
docker run -it --rm -p 9001:9001 --gpus=all roboflow/inference-server:latest
```

サーバーは同じ `/sam3/concept_segment` と `/sam3/visual_segment` 上記で説明したエンドポイントを `http://localhost:9001`.

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

```bash
pip install "inference-gpu[sam3]"
```

```python
import os

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

from inference.core.entities.requests.sam3 import Sam3Prompt
from inference.models.sam3 import SegmentAnything3

model = SegmentAnything3(model_id="sam3/sam3_final")

prompts = [
    # 概念のすべてのインスタンスをセグメントする
    Sam3Prompt(type="text", text="人"),
    # 1つの例示オブジェクトを囲み、類似するすべてのインスタンスをセグメントする。
    # box_labels: 1 = 正の例示、0 = 負の例示。
    Sam3Prompt(
        type="visual",
        boxes=[Sam3Prompt.Box(x=1409, y=705, width=112, height=183)],
        box_labels=[1],
    ),
]

response = model.segment_image(
    image="path/to/your/image.jpg",
    prompts=prompts,
    output_prob_thresh=0.5,
    format="polygon",  # または "rle", "json"
)

for prompt_result in response.prompt_results:
    print(prompt_result.echo.text, len(prompt_result.predictions), "インスタンス")
```

重みは初回使用時に自動でダウンロードされます。

### Pythonでの対話的セグメンテーション

`Sam3ForInteractiveImageSegmentation` は、SAM2風のポイントとボックスのインターフェースを実装しており、人手介在によるマスクの微調整に使えます：

```python
from inference.models.sam3 import Sam3ForInteractiveImageSegmentation

model = Sam3ForInteractiveImageSegmentation(model_id="sam3/sam3_final")

embedding, img_shape, image_id = model.embed_image(image="path/to/image.jpg")

masks, scores, logits = model.segment_image(
    image_id=image_id,
    prompts={"points": [{"x": 500, "y": 400, "positive": True}]},
)
```

## WorkflowsでSAM3を使う

Workflowsには2種類のSAM3画像ブロックがあります： [Workflows](https://docs.roboflow.com/workflows):

* **SAM 3** は概念セグメンテーションを実行します。欲しいクラスを `class_names` （例： `["人", "乗り物"]`）に入力すると、このブロックは他のステップが利用できるインスタンスセグメンテーション予測を出力します。
* **SAM 3 Interactive** はプロンプト可能な視覚セグメンテーションを実行します。ラベル付きポイント（種類 `labeled_points`）を入力します。例： `[{"x": 320, "y": 240, "positive": true}]`。また、必要に応じて別のモデルの検出結果を `boxes` フィールドに接続できます。各ボックスは個別のプロンプトになり、そのクラス名は予測マスクに引き継がれます。

### 動画トラッキング

この **SAM3 Video Tracker** ブロック（`roboflow_core/sam3_video@v1`）は、SAM3のストリーミング概念トラッカーをフレームごとに実行します。概念は次のテキストとして指定します： `class_names`、 `tracker_id`、モデルは各フレームで検出とトラッキングを統合して実行します。概念に一致するオブジェクトは安定した `threshold`、デフォルト `0.5`).

* **状態を保持し、ローカルのみで動作します。** 1つのトラッキングセッションが `video_metadata.video_identifier`ごとに保持されます。このブロックには `WORKFLOWS_STEP_EXECUTION_MODE=local`、GPU、および永続的なWebRTCセッションが必要です。
* **プロンプトのスケジューリングはありません。** 概念プロンプトはセッションごとに1回登録されます。セッションは、ストリームが再起動するか `class_names` が変わる場合にのみ再シードされます。検出器駆動（ボックスプロンプト）の動画トラッキングには、次の上のSAM2 Video Trackerブロックを使ってください： [SAM2ページ](/models/ja/supported-models/sam2.md)。これも次を受け付けます： `sam3trackervideo` として `model_id`.
* **モデル。** `model_id` のデフォルトは `sam3video`です。これはSAM3 videoのHuggingFace Transformers版で、フレームごとのストリーミングインターフェースを提供します。ネイティブの `sam3` パッケージの動画予測器は、動画全体を事前に必要とするため、ライブストリームには使用できません。

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

WORKFLOW = {
    "version": "1.0",
    "inputs": [{"type": "InferenceImage", "name": "image"}],
    "steps": [
        {
            "type": "roboflow_core/sam3_video@v1",
            "name": "tracker",
            "images": "$inputs.image",
            "class_names": ["人", "フォークリフト"],
            "threshold": 0.5,
        },
    ],
    "outputs": [
        {
            "type": "JsonField",
            "name": "predictions",
            "selector": "$steps.tracker.predictions",
        }
    ],
}

client = InferenceHTTPClient(
    api_url="http://localhost:9001",
    api_key="YOUR_API_KEY",
).configure(InferenceConfiguration(api_key_transport="header"))

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-3D（ベータ）

SAM3-3Dは、2D画像とマスクを3Dアセット、つまりメッシュとガウシアンスプラットに変換します。

{% hint style="warning" %}
SAM3-3Dはベータ版です。次の場合にのみ利用できます： `SAM3_3D_OBJECTS_ENABLED` フラグが設定されており、32 GB以上のVRAMを持つGPUが必要で、次を通して実行されます： `inference` パッケージまたはローカルのInferenceサーバー（Serverless Cloud APIにはありません）。
{% endhint %}

依存関係をインストールします（Python 3.10推奨）：

```bash
pip install --no-cache-dir --no-build-isolation -r requirements/requirements.sam3_3d.txt
```

または、3D対応GPUコンテナをビルドして実行します：

```bash
docker build -t roboflow/roboflow-inference-server-gpu:dev -f docker/dockerfiles/Dockerfile.onnx.gpu.3d .
docker run --gpus all -p 9001:9001 roboflow/roboflow-inference-server-gpu:dev
```

**入力。** RGB画像と `mask_input`、オブジェクト領域を定義します。マスクは次の形式で受け付けられます：バイナリアレイ（`(H, W)` または `(N, H, W)`）、COCOのフラットポリゴン、点対ポリゴン、RLE辞書、または `sv.Detections` SAM2または別のセグメンテーションモデルのオブジェクト。

**出力。** `mesh_glb` （結合されたシーンメッシュ、GLB）、 `gaussian_ply` （結合されたガウシアンスプラット、PLY）、 `objects` （オブジェクトごとの `mesh_glb`, `gaussian_ply`、 `metadata` 回転、並進、スケールのメタデータ）、および `時間`.

```python
import os

os.environ["SAM3_3D_OBJECTS_ENABLED"] = "true"
os.environ["SPARSE_ATTN_BACKEND"] = "flash_attn"
os.environ["ATTN_BACKEND"] = "flash_attn"

from inference import get_model
from inference.core.entities.requests.sam3_3d import Sam3_3D_Objects_InferenceRequest

model = get_model("sam3-3d-objects", api_key="YOUR_API_KEY")

request = Sam3_3D_Objects_InferenceRequest(
    image={"type": "file", "value": "image.jpg"},
    mask_input=mask_polygons,  # ポリゴン、バイナリマスク、またはRLE
)

response = model.infer_from_request(request)

if response.mesh_glb is not None:
    with open("out_mesh.glb", "wb") as f:
        f.write(response.mesh_glb)

for index, obj in enumerate(response.objects):
    if obj.gaussian_ply is not None:
        with open(f"out_object_{index}.ply", "wb") as f:
            f.write(obj.gaussian_ply)
```

設定 `SPARSE_ATTN_BACKEND` と `ATTN_BACKEND` に `flash_attn` パイプラインを高速化します。Workflowsでは、SAM3-3Dはローカル実行とリモート実行を、 `sam3_3d_infer()` クライアントメソッドまたは `/sam3_3d/infer` エンドポイント。

## 関連項目

* [SAM2](/models/ja/supported-models/sam2.md) - ポイントおよびボックスによるプロンプト付きセグメンテーションと、検出器起点の動画トラッキング。
* [Segment Anything（SAM）](/models/ja/supported-models/sam.md) - 元の単一オブジェクトモデル。
