> 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/hi/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`, जो दिए गए प्रॉम्प्ट के लिए instance segmentation masks लौटाता है

## कोड नमूना

SAM2 को सीधे HTTP एंडपॉइंट के माध्यम से चलाएँ, `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) और इसे अपने shell के लिए उपलब्ध कराएँ:

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

{% endstep %}

{% step %}

### मॉडल चलाएँ

कॉल करें `/sam2/segment_image` endpoint के साथ `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) और इसे अपने shell के लिए उपलब्ध कराएँ:

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

{% endstep %}

{% step %}

### निर्भरताएँ इंस्टॉल करें

ये पैकेज मॉडल को कॉल करते हैं और उसके परिणामों को ड्रॉ करते हैं:

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

{% endstep %}

{% step %}

### मॉडल चलाएँ

एकल positive point प्रॉम्प्ट के साथ सेगमेंटेशन एंडपॉइंट को कॉल करें, लौटाए गए polygons को supervision के साथ detections में बदलें, और input image पर mask ड्रॉ करके एक annotated 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` उन polygon predictions को पढ़ता है जो SAM2 और SAM3 दोनों लौटाते हैं, इसलिए वही कॉल किसी भी मॉडल के आउटपुट को decode करती है।

<figure><img src="/files/2c8b4c4c13cfd9bda984c65a837ea84378cc0ce9" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}
{% endtab %}
{% endtabs %}

## इनफ़रेंस गति

विलंबता मापी गई [Roboflow Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted) पर 1x NVIDIA L4, batch size 1, warmup के बाद औसत।

<table data-search="false"><thead><tr><th>मॉडल</th><th>Latency (ms)</th></tr></thead><tbody><tr><td><code>sam2</code></td><td>177.7</td></tr></tbody></table>

से मापा गया `segment_image` पर `hiera_large` checkpoint. SAM2 image embeddings को कैश करता है, इसलिए यह figure हर कॉल पर एक ताज़ा इमेज का उपयोग करती है और पूरे encode plus decode लागत को दर्शाती है। पहले से encoded इमेज को दोबारा prompt करना काफी तेज़ होता है।

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

* `https://serverless.roboflow.com` सर्वरलेस होस्टेड API के लिए।
* `http://localhost:9001` एक स्थानीय [Inference](https://docs.roboflow.com/deployment/self-hosted/self-hosted) server के लिए।
* आपका [समर्पित परिनियोजन](https://docs.roboflow.com/deployment/roboflow-cloud/dedicated-deployments) एक निजी endpoint के लिए URL।
  {% endhint %}

embedding caching और box prompts सहित अतिरिक्त उपयोग विवरण के लिए, देखें [इनफ़रेंस दस्तावेज़ीकरण](https://docs.roboflow.com/deployment/self-hosted/self-hosted).

## Inference (self-hosted) के साथ उपयोग करें

SAM2 को सीधे भी लोड किया जा सकता है [`इनफ़रेंस`](https://docs.roboflow.com/deployment/self-hosted/self-hosted) package के साथ, या ऐसे GPU container से serve किया जा सकता है जिसे आप स्वयं चलाते हैं। यह सही तरीका है जब आप images को अपने hardware पर रखना चाहते हैं, या जब आप एक ही image को कई बार re-prompt कर रहे हों।

### Docker में चलाएँ

का root से SAM2 image बनाएँ [inference repository](https://github.com/roboflow/inference):

```bash
docker build -f docker/dockerfiles/Dockerfile.sam2 -t sam2 .
```

फिर एक server शुरू करें जो SAM2 endpoints को expose करता हो:

```bash
docker run -it --rm -v /tmp/cache/:/tmp/cache/ --gpus=all --net=host sam2
```

Point `api_url` उस server पर (`http://localhost:9001`) और ऊपर दिए गए code samples बिना बदले काम करते हैं।

{% hint style="warning" %}
flash attention के साथ SAM2 में [एक ज्ञात समस्या है](https://github.com/facebookresearch/sam2/issues/48) कुछ GPUs पर, जिनमें L4 और A100 शामिल हैं। उस thread से fix लागू करें, या ऊपर दिया गया Docker image उपयोग करें, जो इसे पहले से संभालता है।
{% endhint %}

### Python में model लोड करें

```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"

# image embedding को पहले से गणना करके कैश करें
embedding, img_shape, image_id = model.embed_image(image_path)

# cached embedding का उपयोग करके segment करें
raw_masks, raw_low_res_masks = model.segment_image(image_path)
raw_masks = raw_masks >= model.predictor.mask_threshold
poly_masks = masks2poly(raw_masks)
```

Embeddings स्वतः कैश हो जाते हैं, इसलिए आप जैसे ही जान लें कि आपको इसकी आवश्यकता होगी, एक image को embed कर सकते हैं और बाद में कम लागत पर re-prompt कर सकते हैं।

एक mask को refine करने के लिए, एक negative point भेजें (`"positive": False`) ताकि एक region को exclude किया जा सके:

```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 में वीडियो tracking

यह **SAM2 Video Tracker** block (`roboflow_core/segment_anything_2_video@v1`) SAM2 के streaming video predictor को frame by frame चलाता है, और प्रति-वीडियो temporal memory बनाए रखता है ताकि object identities frames के बीच बनी रहें। इसे upstream detector से bounding boxes दें: यह प्रत्येक box को mask में बदलता है और बाद के frames पर उसे track करता है, और segmentation predictions emit करता है जिनका `tracker_id` SAM2 द्वारा object को follow करने तक स्थिर रहता है। Masks detection के class name, class id, और confidence को inherit करते हैं जिसने उन्हें prompt किया था।

* **Stateful और केवल local।** यह block प्रत्येक के लिए एक tracking session रखता है `video_metadata.video_identifier`, इसलिए यह कई streams को multiplex कर सकता है, लेकिन session process memory में रहता है। इसके लिए `WORKFLOWS_STEP_EXECUTION_MODE=local`, एक GPU, और एक persistent WebRTC session आवश्यक है। यह अलग-अलग stateless HTTP requests के लिए उपयुक्त नहीं है।
* **Prompt scheduling।** `prompt_mode` यह नियंत्रित करता है कि detector boxes को prompts के रूप में कब consume किया जाए: `first_frame` (default) session में एक बार prompt करता है, फिर चुपचाप track करता है; `every_n_frames` हर `prompt_interval` frames पर फिर से seed करता है, जिससे scene में आए objects पकड़े जाते हैं; `every_frame` हर frame पर फिर से seed करता है, और stable tracker ids के साथ प्रति-frame detection-to-mask adapter के रूप में काम करता है।
* **Model variants।** `model_id` Hiera backbone का चयन करता है: `sam2video/tiny`, `sam2video/small` (default), `sam2video/base-plus`, `sam2video/large`. यह block `sam3trackervideo`, SAM3 का visually prompted tracker, को भी स्वीकार करता है, जो बहुत बड़े backbone के साथ वही box-prompt contract उपयोग करता है। यह लंबी videos और भीड़भाड़ वाले scenes में अधिक compute लागत पर identities को बेहतर बनाए रखता है: इसे maximum-quality tier मानें और `sam2video` sizes को speed tiers मानें।

```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()
```

टेक्स्ट prompts से open-vocabulary video tracking के लिए, बिना upstream detector के, पर SAM3 Video Tracker block देखें [SAM3 page](/models/hi/supported-models/sam3.md).

### वर्कफ़्लोज़ में निष्पादन मोड

जब image Workflow में उपयोग किया जाता है, SAM2 दो modes में से एक में चलता है:

* **लोकल निष्पादन**: model आपके Inference server पर चलता है (GPU की दृढ़ता से अनुशंसा की जाती है)।
* **रिमोट निष्पादन**: मॉडल को एक रिमोट Inference सर्वर पर HTTP के माध्यम से `sam2_segment_image()` क्लाइंट विधि।

## यह भी देखें

* [SAM3](/models/hi/supported-models/sam3.md) - टेक्स्ट prompt से किसी concept के हर instance को segment करता है।
* [Segment Anything (SAM)](/models/hi/supported-models/sam.md) - मूल single-object model।
