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

# SAM2

हम Meta के [Segment Anything Model 2](https://github.com/facebookresearch/sam2) हमारे माध्यम से inferencing [Serverless Hosted API](/roboflow/roboflow-hi/deploy/serverless-hosted-api-v2.md). SAM2 एक promptable visual segmentation model है जो prompts के रूप में points और bounding boxes स्वीकार करता है। हम दो SAM2 endpoints प्रदान करते हैं:

* [/sam2/embed\_image](#post-sam2-embed_image), जो एक image embedding उत्पन्न करता है और cache करता है
* [/sam2/segment\_image](#post-sam2-segment_image), जो दिए गए prompts के लिए instance segmentation masks लौटाता है

## कोड सैंपल

को कॉल करें `/sam2/segment_image` endpoint को सीधे `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 के माध्यम से वही call। dependencies install करें:

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

नीचे एक code sample है जो segmentation endpoint को एक single positive point prompt के साथ call करता है, लौटाए गए polygons को binary mask में decode करता है, और input image पर mask के साथ एक annotated PNG सहेजता है। Pass [Roboflow's API Key](https://app.roboflow.com/settings/api) के माध्यम से `API_KEY` env variable.

```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/ef38c3fc92df340c49528f86f2e6998029fbba00" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Set `api_url` को अपने deployment target से मिलाने के लिए:

* `https://serverless.roboflow.com` Serverless Hosted API के लिए।
* `http://localhost:9001` एक local [Inference](https://inference.roboflow.com/) server.
* आपका [Dedicated Deployment](/roboflow/roboflow-hi/deploy/dedicated-deployments.md) एक private endpoint के लिए URL.
  {% endhint %}

अतिरिक्त usage details के लिए, जिसमें embedding caching और box prompts शामिल हैं, देखें the [Inference documentation](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-hi/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.
