> 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`, 주어진 프롬프트에 대한 인스턴스 분할 마스크를 반환합니다

## 코드 샘플

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

## 추론 속도

다음을 사용해 측정한 지연 시간 [Roboflow Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted) 1x NVIDIA L4, 배치 크기 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 비디오 트래커** 블록 (`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` 매 프레임마다 다시 시드하여 안정적인 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 페이지의](/models/ko/supported-models/sam3.md).

### Workflows의 실행 모드

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

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

## 참고

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