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

# SAM3

Meta의 [Segment Anything Model 3](https://github.com/facebookresearch/sam3) 추론을 지원합니다. 당사의 [서버리스 호스팅 API](https://docs.roboflow.com/deployment/roboflow-cloud/serverless-api). 두 가지 SAM3 엔드포인트를 제공합니다:

{% hint style="info" %}
Roboflow에서 SAM3 모델 학습은 유료 [플랜에서](https://docs.roboflow.com/platform/billing-and-plans/plans) 다음을 포함하는 [사용량 기반 청구](https://docs.roboflow.com/platform/billing-and-plans/credits). 여기에서 SAM3 아키텍처의 "기능 요청" 버튼을 통해 기능 사용 권한을 요청할 수 있습니다 [학습 흐름](/models/ko/readme.md).
{% endhint %}

* [프롬프트 기반 개념 세그멘테이션](#concept-segmentation-pcs) (**PCS**)는 이미지에서 개념의 모든 인스턴스를 세그멘테이션합니다. 개념은 텍스트 프롬프트, 예시 박스 또는 둘 다로 설명됩니다.
* [프롬프트 기반 시각 세그멘테이션](#visual-segmentation-pvs) (**PVS**)는 SAM2 스타일로, 포인트 또는 박스에서 요청당 하나의 객체를 대화형으로 세그멘테이션합니다.

이 표를 사용하여 엔드포인트를 선택하세요:

<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>예시 객체 하나를 둘러싼 박스</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>특정 객체 하나에 대한 클릭 또는 박스</td><td>해당 객체만의 마스크</td><td><code>/sam3/visual_segment</code></td></tr></tbody></table>

귀하의 [API 키](https://app.roboflow.com/settings/api) 다음으로 `api_key` 모든 요청의 쿼리 매개변수로 전달하세요.

## 개념 세그멘테이션(PCS)

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

의 각 항목 `prompts` 는 하나의 개념을 설명합니다. 응답에는 하나의 `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": "person"},
        {"type": "text", "text": "backpack"},
    ],
    "output_prob_thresh": 0.5,
    "format": "polygon",  # 또는 "rle"
}

response = requests.post(
    "https://serverless.roboflow.com/sam3/concept_segment",
    params={"api_key": os.environ["ROBOFLOW_API_KEY"]},
    json=payload,
)
for prompt_result in response.json()["prompt_results"]:
    print(prompt_result["echo"], len(prompt_result["predictions"]), "instances")
```

이미지는 다음과 같이 인라인으로도 전송할 수 있습니다 `{"type": "base64", "value": "<BASE64_IMAGE>"}`.

### 예시 박스 프롬프트

텍스트 대신 예시를 프롬프트로 사용할 수 있습니다. 즉, 예시 객체 하나를 둘러싼 박스입니다. 모델은 박스로 둘러싼 객체뿐 아니라 예시와 일치하는 모든 인스턴스를 찾습니다.

```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",
}
```

박스는 절대 픽셀 좌표를 사용합니다. 두 가지 형식이 허용됩니다:

* `{"x": ..., "y": ..., "width": ..., "height": ...}` 여기서 `x`, `y` 는 왼쪽 상단 모서리입니다
* `{"x0": ..., "y0": ..., "x1": ..., "y1": ...}` 명시적 모서리용

`box_labels` 은 다음 경우 필수입니다 `boxes` 가 설정되어 있으며 박스당 하나의 항목이 있어야 합니다: `1` 는 양성 예시를 표시합니다(이와 같은 객체 찾기), `0` 는 음성 예시를 표시합니다(이와 같은 객체 제외).

### 텍스트와 예시 프롬프트 결합

하나의 프롬프트에 텍스트와 예시 박스를 모두 포함할 수 있습니다. 이는 시각적 예시로 텍스트 개념을 좁히거나 음성 예시로 유사 객체를 제외하는 데 유용합니다:

```python
payload = {
    "image": {"type": "url", "value": "https://media.roboflow.com/inference/people-walking.jpg"},
    "prompts": [
        {
            "type": "visual",
            "text": "person",
            "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",
}
```

여기서 모델은 첫 번째(양성) 예시와 일치하는 사람을 세그멘테이션하고, 두 번째(음성) 예시와 유사한 인스턴스는 억제합니다.

## 시각 세그멘테이션(PVS)

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

PVS는 클릭 또는 박스로 지정된 특정 객체 하나를 세그멘테이션합니다. 대화형 인간 참여형 마스크 정제에는 이를 사용하고, 개념의 모든 인스턴스가 필요할 때는 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",
    params={"api_key": os.environ["ROBOFLOW_API_KEY"]},
    json=payload,
)
prediction = response.json()["predictions"][0]
print(prediction["confidence"], len(prediction["masks"]), "polygons")
```

프롬프트에는 `포인트`,  `박스`, 또는 둘 다 포함할 수 있습니다:

* `포인트` 는 절대 픽셀 좌표입니다. `"positive": true` 은 클릭한 영역을 포함하고, `false` 는 이를 제외합니다. 마스크를 정제하려면 포인트를 더 추가하세요.
* `박스` 는 중심 기준 좌표를 사용합니다: `x`, `y` 는 PCS 박스가 왼쪽 상단 기준인 것과 달리 박스 중심입니다.

응답에는 프롬프트에 대해 신뢰도가 가장 높은 단일 마스크가 포함됩니다. `multimask_output` 는 모델이 생성하는 내부 마스크 제안의 수를 제어하지만(true일 때 3개), 응답에는 항상 최상의 제안이 선택됩니다.

{% hint style="warning" %}
요청당 하나의 프롬프트를 전송하세요. 현재 하나의 PVS 요청에 여러 프롬프트를 포함하면 하나의 예측만 반환됩니다.
{% endhint %}

OpenCV를 사용하는 대화형 데모는 이 [GitHub Gist](https://gist.github.com/Erol444/4cbc33c6ac52d83c63f6f9d86ca8a7a4)를 참조하세요. 이 동영상에서 사용되었습니다:

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

## 추론 속도

다음을 사용하여 측정한 지연 시간 [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>sam3</code></td><td>251.4</td></tr></tbody></table>

단일 텍스트 프롬프트의 개념 세그멘테이션으로 측정했습니다.

## 엔드포인트

## 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"}}}}
```

## Inference(셀프 호스팅)와 함께 사용

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="person"),
    # 예시 객체 하나를 박스로 지정하고 유사한 모든 인스턴스를 세그멘테이션합니다.
    # 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), "instances")
```

가중치는 처음 사용할 때 자동으로 다운로드됩니다.

### 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](https://docs.roboflow.com/workflows):

* **SAM 3** 는 개념 세그멘테이션을 실행합니다. 원하는 클래스를 다음에 입력하세요 `class_names` (예: `["person", "vehicle"]`) 그러면 블록은 다른 단계에서 사용할 수 있는 인스턴스 세그멘테이션 예측을 출력합니다.
* **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`).

* **상태를 유지하며 로컬 전용입니다.** 추적 세션 하나가 다음마다 유지됩니다 `video_metadata.video_identifier`. 이 블록에는 다음이 필요합니다 `WORKFLOWS_STEP_EXECUTION_MODE=local`, GPU 및 영구적인 WebRTC 세션.
* **프롬프트 스케줄링 없음.** 개념 프롬프트는 세션당 한 번 등록되며, 스트림이 재시작되거나 다음이 `class_names` 변경될 때만 세션이 다시 시드됩니다. 탐지기 기반(박스 프롬프트) 비디오 추적에는 다음의 SAM2 Video Tracker 블록을 사용하세요 [SAM2 페이지](/models/ko/supported-models/sam2.md), 이 블록은 또한 다음을 허용합니다 `sam3trackervideo` 를 `model_id`.
* **모델로 사용합니다.** `model_id` 의 기본값은 `sam3video`, 프레임별 스트리밍 인터페이스를 노출하는 SAM3 비디오의 HuggingFace transformers 포트입니다. 네이티브 `sam3` 패키지의 비디오 예측기는 전체 비디오를 미리 요구하므로 라이브 스트림에 사용할 수 없습니다.

```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/sam3_video@v1",
            "name": "tracker",
            "images": "$inputs.image",
            "class_names": ["person", "forklift"],
            "threshold": 0.5,
        },
    ],
    "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-3D(베타)

SAM3-3D는 2D 이미지와 마스크를 메시 및 가우시안 스플랫이라는 3D 에셋으로 변환합니다.

{% hint style="warning" %}
SAM3-3D는 베타 버전입니다. 다음 경우에만 사용할 수 있습니다 `SAM3_3D_OBJECTS_ENABLED` 플래그가 설정되어 있고, VRAM 32GB 이상의 GPU가 필요하며, 다음을 통해 실행됩니다 `inference` 패키지 또는 로컬 Inference 서버(서버리스 호스팅 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` (회전, 이동 및 스케일 포함), 그리고 `time`.

```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/ko/supported-models/sam2.md) - 포인트 및 박스 프롬프트 분할, 그리고 탐지기 기반 비디오 추적.
* [Segment Anything (SAM)](/models/ko/supported-models/sam.md) - 원래의 단일 객체 모델.
