> 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/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 엔드포인트를 두 개 제공합니다:

* `/sam2/embed_image`, 이미지 임베딩을 생성하고 캐시합니다
* `/sam2/segment_image`, 주어진 프롬프트에 대한 인스턴스 분할 마스크를 반환합니다

## SAM2 API

다음과 같이 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' \
  --header "Authorization: Bearer $ROBOFLOW_API_KEY" \
  --data '{
    "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, InferenceConfiguration

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"],
).configure(InferenceConfiguration(api_key_transport="header"))

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/2de433d197dbf4fc2fe25c17fe582b56b12c89e5" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}
{% endtab %}
{% endtabs %}

## SAM2 추론 속도

다음을 사용하여 측정한 지연 시간 [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` 는 서버리스 클라우드 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` at that server (`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 비디오 트래커** 블록(`roboflow_core/segment_anything_2_video@v1`)은 SAM2의 스트리밍 비디오 예측기를 프레임별로 실행하며, 비디오별 시간 메모리를 유지해 객체 ID가 프레임 간에 지속되도록 합니다. 상위 탐지기의 경계 상자를 입력하면 각 박스를 마스크로 변환하고 이후 프레임에서 추적하며, 분할 예측을 내보내는데 그 예측의 `tracker_id` SAM2가 객체를 추적하는 동안 유지됩니다. 마스크는 이를 유도한 탐지의 클래스 이름, 클래스 ID, 신뢰도를 상속합니다.

* **상태 유지 방식이며 로컬 전용입니다.** 이 블록은 각 `video_metadata.video_identifier`, 따라서 여러 스트림을 다중화할 수 있지만 세션은 프로세스 메모리에 존재합니다. 다음이 필요합니다: `WORKFLOWS_STEP_EXECUTION_MODE=local`, GPU, 그리고 지속적인 WebRTC 세션이 필요합니다. 별도의 무상태 HTTP 요청에는 적합하지 않습니다.
* **프롬프트 스케줄링.** `prompt_mode` 탐지 박스가 프롬프트로 사용되는 시점을 제어합니다: `first_frame` (기본값) 세션당 한 번만 프롬프트하고 이후에는 조용히 추적합니다; `every_n_frames` 매 `prompt_interval` 프레임마다 다시 시드하여 장면에 들어온 객체를 포착합니다; `every_frame` 매 프레임마다 다시 시드하여 안정적인 추적 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/ko/supported-models/sam3.md).

### Workflows의 실행 모드

이미지 워크플로에서 사용할 때 SAM2는 다음 두 모드 중 하나로 실행됩니다:

* **로컬 실행**: 모델이 사용자의 Inference 서버에서 실행됩니다(GPU 강력 권장).
* **원격 실행**: 모델이 원격 Inference 서버에서 HTTP로 다음을 통해 호출됩니다: `sam2_segment_image()` 클라이언트 메서드.

## 또한 참조

* [SAM3](/models/ko/supported-models/sam3.md) - 텍스트 프롬프트에서 개념의 모든 인스턴스를 분할합니다.
* [Segment Anything (SAM)](/models/ko/supported-models/sam.md) - 원래의 단일 객체 모델.
