> 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).

미세 조정된 SAM3 모델은 서버리스 클라우드 API에서 실행할 수 없습니다. 다음에 배포하세요 [전용 배포](https://docs.roboflow.com/deployment/roboflow-cloud/dedicated-deployments) 또는 [자체 호스팅 추론](https://docs.roboflow.com/deployment/self-hosted/self-hosted). 호스팅되는 `sam3` 이 페이지의 엔드포인트는 영향을 받지 않습니다.
{% endhint %}

* [프롬프트 기반 개념 세분화](#sam3-concept-segmentation-pcs) (**PCS**), 이미지 내 개념의 모든 인스턴스를 세분화합니다. 개념은 텍스트 프롬프트, 예시 상자 또는 둘 다로 설명됩니다.
* [프롬프트 기반 시각적 세분화](#sam3-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) 다음의 `Authorization: Bearer` 모든 요청의 헤더에 포함하세요. 레거시 `api_key` 쿼리 매개변수도 계속 작동하지만 권장되지 않습니다.

## SAM3 개념 세분화(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",
    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>"}`.

### 예시 상자 프롬프트

텍스트 대신 예시, 즉 하나의 예시 객체 주위 상자로 프롬프트할 수 있습니다. 모델은 상자 안의 객체뿐 아니라 예시와 일치하는 모든 인스턴스를 찾습니다.

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

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

## SAM3 시각적 세분화(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",
    headers={"Authorization": f"Bearer {os.environ['ROBOFLOW_API_KEY']}"},
    json=payload,
)
prediction = response.json()["predictions"][0]
print(prediction["confidence"], len(prediction["masks"]), "폴리곤")
```

프롬프트에는 다음을 포함할 수 있습니다 `점`, 하나의 `상자`, 또는 둘 다:

* `점` 는 절대 픽셀 좌표입니다. `"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>" %}

## SAM3 추론 속도

다음을 사용하여 측정한 지연 시간 [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 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"}}}}
```

## 자체 호스팅 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="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), "인스턴스")
```

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

### 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 사용

다음에서 두 개의 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 비디오 트래커** 블록(`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 비디오 트래커 블록을 사용하세요 [SAM2 페이지](/models/ko/supported-models/sam2.md), 이 블록은 또한 다음을 허용합니다 `sam3trackervideo` 을 다음으로 `model_id`.
* **모델.** `model_id` 의 기본값은 `sam3video`, 프레임별 스트리밍 인터페이스를 노출하는 SAM3 비디오의 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": ["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",
).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` 플래그가 설정되어 있어야 하며, 32GB 이상의 VRAM을 갖춘 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) - 원래의 단일 객체 모델.
