> 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/roboflow/roboflow-ko/deploy/supported-models/sam2.md).

# SAM2

Meta의 [Segment Anything Model 2](https://github.com/facebookresearch/sam2) 추론은 우리의 [Serverless Hosted API](/roboflow/roboflow-ko/deploy/serverless-hosted-api-v2.md). SAM2는 포인트와 바운딩 박스를 프롬프트로 받는 프롬프트 가능 비주얼 세그멘테이션 모델입니다. 우리는 두 개의 SAM2 엔드포인트를 제공합니다:

* [/sam2/embed\_image](#post-sam2-embed_image)로, 이미지 임베딩을 생성하고 캐시합니다
* [/sam2/segment\_image](#post-sam2-segment_image)로, 주어진 프롬프트에 대한 인스턴스 세그멘테이션 마스크를 반환합니다

## 코드 샘플

다음과 함께 HTTP 엔드포인트를 통해 SAM2를 직접 실행하세요 `curl`또는 [`inference-sdk`](https://inference.roboflow.com/inference_helpers/inference_sdk/) 래퍼를 사용하세요.

{% tabs %}
{% tab title="HTTP (curl)" icon="webhook" %}
{% stepper %}
{% step %}

### API Key를 받으세요

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 Key를 받으세요

Roboflow 계정을 만들고, 다음에서 키를 찾으세요: [Roboflow API 설정 페이지](https://app.roboflow.com/settings/api) 그리고 이를 셸에서 사용할 수 있도록 설정하세요:

```bash
export ROBOFLOW_API_KEY="your-key-here"
```

{% endstep %}

{% step %}

### 종속성을 설치하세요

이 패키지들은 모델을 호출하고 결과를 그립니다:

```bash
pip install inference-sdk supervision opencv-python
```

{% endstep %}

{% step %}

### 모델을 실행하세요

단일 양성 포인트 프롬프트로 세그멘테이션 엔드포인트를 호출하고, 반환된 폴리곤을 supervision으로 detections로 변환한 다음, 마스크가 입력 이미지 위에 그려진 주석 PNG를 저장합니다:

```python
import os
import cv2
import numpy as np
import requests
import supervision as sv
from inference_sdk import InferenceHTTPClient

content = requests.get("https://media.roboflow.com/quickstart/traffic.jpg").content
image = cv2.imdecode(np.frombuffer(content, np.uint8), cv2.IMREAD_COLOR)
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/bf80a036ffe8f52a80c80cde2cd04218d587fb35" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}
{% endtab %}
{% endtabs %}

## 추론 속도

다음 기준으로 측정한 지연 시간 [Roboflow Inference](https://inference.roboflow.com/) 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://inference.roboflow.com/) 서버용입니다.
* 귀하의 [Dedicated Deployment](/roboflow/roboflow-ko/deploy/dedicated-deployments.md) 비공개 엔드포인트용 URL입니다.
  {% endhint %}

추가 사용 방법, 임베딩 캐싱 및 박스 프롬프트에 대한 자세한 내용은 다음을 참조하세요 [Inference 문서](https://inference.roboflow.com/).
