> 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), 이는 주어진 프롬프트에 대한 인스턴스 세그멘테이션 마스크를 반환합니다

## 코드 샘플

다음을 `/sam2/segment_image` 엔드포인트에 직접 호출합니다 `curl`:

```bash
curl --location 'https://serverless.roboflow.com/sam2/segment_image' \
  --header 'Content-Type: application/json' \
  --data '{
    "api_key": "YOUR_API_KEY",
    "image": {"type": "url", "value": "https://storage.googleapis.com/com-roboflow-marketing/notebooks/examples/bicycle.png"},
    "prompts": {"prompts": [{"points": [{"x": 300, "y": 250, "positive": true}]}]},
    "sam2_version_id": "hiera_tiny"
  }'
```

SDK를 통한 동일한 호출입니다. 다음 종속성을 설치하세요:

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

아래는 단일 양성 포인트 프롬프트로 세그멘테이션 엔드포인트를 호출하고, 반환된 폴리곤을 이진 마스크로 디코딩한 뒤, 입력 이미지 위에 마스크를 그려 주석이 달린 PNG를 저장하는 코드 샘플입니다. 다음을 전달하세요 [Roboflow의 API Key](https://app.roboflow.com/settings/api) 를 `API_KEY` 환경 변수를 통해.

```python
import os
import urllib.request

import cv2
import numpy as np
import supervision as sv
from inference_sdk import InferenceHTTPClient

IMAGE_URL = "https://storage.googleapis.com/com-roboflow-marketing/notebooks/examples/bicycle.png"
IMAGE_PATH = "bicycle.png"
OUTPUT_PATH = "bicycle_annotated.png"

urllib.request.urlretrieve(IMAGE_URL, IMAGE_PATH)
image = cv2.imread(IMAGE_PATH)
height, width = image.shape[:2]

client = InferenceHTTPClient(
    api_url="https://serverless.roboflow.com",
    api_key=os.getenv("API_KEY"),
)

result = client.sam2_segment_image(
    inference_input=IMAGE_PATH,
    prompts=[
        {"points": [{"x": 300, "y": 250, "positive": True}]}
    ],
    sam2_version_id="hiera_tiny",
)

masks, xyxys, confidences = [], [], []
for pred in result["predictions"]:
    contours = [np.array(poly, dtype=np.int32) for poly in pred.get("masks", []) if poly]
    if not contours:
        continue
    mask = np.zeros((height, width), dtype=np.uint8)
    cv2.fillPoly(mask, contours, 1)
    ys, xs = np.where(mask > 0)
    if xs.size == 0:
        continue
    masks.append(mask.astype(bool))
    xyxys.append([xs.min(), ys.min(), xs.max(), ys.max()])
    confidences.append(pred.get("confidence", 1.0))

detections = sv.Detections(
    xyxy=np.array(xyxys, dtype=float),
    mask=np.stack(masks, axis=0),
    class_id=np.zeros(len(masks), dtype=int),
    confidence=np.array(confidences, dtype=float),
)

annotated = sv.MaskAnnotator().annotate(scene=image.copy(), detections=detections)
cv2.imwrite(OUTPUT_PATH, annotated)
```

<figure><img src="/files/bf80a036ffe8f52a80c80cde2cd04218d587fb35" alt=""><figcaption></figcaption></figure>

{% 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/).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.roboflow.com/roboflow/roboflow-ko/deploy/supported-models/sam2.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
