> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-hi/image-processing/segment-anything.md).

# Segment Anything

GPU पर सटीक छवि विभाजन के लिए मेटा का SAM उपयोग करें।

{% hint style="success" %}
सभी उदाहरण GPU सर्वरों पर चलाए जा सकते हैं जिन्हें द्वारा किराए पर लिया गया है [CLORE.AI मार्केटप्लेस](https://clore.ai/marketplace).
{% endhint %}

## CLORE.AI पर किराये पर लेना

1. पर जाएँ [CLORE.AI मार्केटप्लेस](https://clore.ai/marketplace)
2. GPU प्रकार, VRAM, और मूल्य के अनुसार फ़िल्टर करें
3. चुनें **ऑन-डिमांड** (निश्चित दर) या **स्पॉट** (बिड प्राइस)
4. अपना ऑर्डर कॉन्फ़िगर करें:
   * Docker इमेज चुनें
   * पोर्ट सेट करें (SSH के लिए TCP, वेब UI के लिए HTTP)
   * यदि आवश्यक हो तो एनवायरनमेंट वेरिएबल जोड़ें
   * स्टार्टअप कमांड दर्ज करें
5. भुगतान चुनें: **CLORE**, **BTC**, या **USDT/USDC**
6. ऑर्डर बनाएं और डिप्लॉयमेंट का इंतज़ार करें

### अपने सर्वर तक पहुँचें

* कनेक्शन विवरण में खोजें **मेरे ऑर्डर**
* वेब इंटरफेस: HTTP पोर्ट URL का उपयोग करें
* SSH: `ssh -p <port> root@<proxy-address>`

## SAM क्या है?

Segment Anything Model (SAM) कर सकता है:

* छवियों में किसी भी वस्तु को सेगमेंट करना
* प्रॉम्प्ट (पॉइंट्स, बॉक्स, टेक्स्ट) के साथ काम करना
* स्वचालित मास्क उत्पन्न करना
* किसी भी प्रकार की छवि को संभालना

## मॉडल वेरिएंट

| मॉडल              | VRAM | गुणवत्ता   | स्पीड |
| ----------------- | ---- | ---------- | ----- |
| SAM-H (बहुत बड़ा) | 8GB  | सर्वोत्तम  | धीमा  |
| SAM-L (बड़ा)      | 6GB  | बहुत अच्छा | मध्यम |
| SAM-B (बेस)       | 4GB  | अच्छा      | तेज़  |
| SAM2              | 8GB+ | सर्वोत्तम  | मध्यम |

## त्वरित तैनाती

**Docker इमेज:**

```
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel
```

**पोर्ट:**

```
22/tcp
7860/http
```

**कमांड:**

```bash
pip install segment-anything gradio opencv-python && \
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth && \
python -c "
import gradio as gr
import numpy as np
from segment_anything import sam_model_registry, SamPredictor
import cv2

sam = sam_model_registry['vit_h'](checkpoint='sam_vit_h_4b8939.pth').cuda()
predictor = SamPredictor(sam)

def segment(image, evt: gr.SelectData):
    predictor.set_image(image)
    point = np.array([[evt.index[0], evt.index[1]]])
    masks, _, _ = predictor.predict(point_coords=point, point_labels=np.array([1]))
    mask = masks[0]
    colored = np.zeros_like(image)
    colored[mask] = [255, 0, 0]
    result = cv2.addWeighted(image, 0.7, colored, 0.3, 0)
    return result

demo = gr.Interface(fn=segment, inputs=gr.Image(), outputs=gr.Image(), title='Click to Segment')
demo.launch(server_name='0.0.0.0', server_port=7860)
"
```

## अपनी सेवा तक पहुँचना

डिप्लॉयमेंट के बाद, अपना खोजें `http_pub` URL में **मेरे ऑर्डर**:

1. जाएँ **मेरे ऑर्डर** पृष्ठ
2. अपने ऑर्डर पर क्लिक करें
3. खोजें `http_pub` URL (उदा., `abc123.clorecloud.net`)

उपयोग करें `https://YOUR_HTTP_PUB_URL` की बजाय `localhost` नीचे दिए उदाहरणों में।

## इंस्टॉलेशन

```bash
pip install segment-anything opencv-python
```

### मॉडल डाउनलोड करें

```bash

# SAM-H (सबसे अच्छी गुणवत्ता)
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth

# SAM-L (संतुलित)
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth

# SAM-B (तेज़)
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth
```

## Python API

### बिंदुओं के साथ बुनियादी सेगमेंटेशन

```python
from segment_anything import sam_model_registry, SamPredictor
import cv2
import numpy as np

# मॉडल लोड करें
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cuda")

predictor = SamPredictor(sam)

# छवि लोड करें
image = cv2.imread("photo.jpg")
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# छवि सेट करें
predictor.set_image(image_rgb)

# प्वाइंट प्रॉम्प्ट के साथ सेगमेंट करें
input_point = np.array([[500, 375]])  # x, y निर्देशांक
input_label = np.array([1])  # 1 = फोरग्राउंड, 0 = बैकग्राउंड

masks, scores, logits = predictor.predict(
    point_coords=input_point,
    point_labels=input_label,
    multimask_output=True
)

# सर्वश्रेष्ठ मास्क प्राप्त करें
best_mask = masks[np.argmax(scores)]

# मास्क सहेजें
cv2.imwrite("mask.png", best_mask.astype(np.uint8) * 255)
```

### बॉक्स प्रॉम्प्ट

```python

# बाउंडिंग बॉक्स के साथ सेगमेंट करें
input_box = np.array([100, 100, 400, 400])  # x1, y1, x2, y2

masks, scores, _ = predictor.predict(
    box=input_box,
    multimask_output=False
)
```

### कई बिंदु

```python

# कई फोरग्राउंड/बैकग्राउंड बिंदु
input_points = np.array([
    [500, 375],   # बिंदु 1
    [550, 400],   # बिंदु 2
    [100, 100],   # बैकग्राउंड बिंदु
])
input_labels = np.array([1, 1, 0])  # 1=फोरग्राउंड, 0=बैकग्राउंड

masks, scores, _ = predictor.predict(
    point_coords=input_points,
    point_labels=input_labels,
    multimask_output=True
)
```

### बॉक्स + बिंदु संयोजन

```python
masks, scores, _ = predictor.predict(
    point_coords=input_point,
    point_labels=input_label,
    box=input_box,
    multimask_output=False
)
```

## स्वचालित मास्क जनरेशन

सभी संभावित मास्क उत्पन्न करें:

```python
from segment_anything import SamAutomaticMaskGenerator
import cv2

sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cuda")

mask_generator = SamAutomaticMaskGenerator(
    model=sam,
    points_per_side=32,
    pred_iou_thresh=0.86,
    stability_score_thresh=0.92,
    crop_n_layers=1,
    crop_n_points_downscale_factor=2,
    min_mask_region_area=100
)

image = cv2.imread("photo.jpg")
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

masks = mask_generator.generate(image_rgb)

# प्रत्येक मास्क में शामिल होता है:

# - 'segmentation': बाइनरी मास्क

# - 'area': पिक्सेल में मास्क का क्षेत्र

# - 'bbox': बॉन्डिंग बॉक्स

# - 'predicted_iou': गुणवत्ता स्कोर

# - 'stability_score': स्थिरता स्कोर

print(f"Found {len(masks)} masks")
```

### सभी मास्क का विज़ुअलाइज़ेशन

```python
import matplotlib.pyplot as plt

def show_masks(image, masks):
    plt.figure(figsize=(20, 20))
    plt.imshow(image)

    sorted_masks = sorted(masks, key=lambda x: x['area'], reverse=True)

    for mask in sorted_masks:
        m = mask['segmentation']
        color = np.random.random(3)
        colored = np.zeros((*m.shape, 4))
        colored[m] = [*color, 0.5]
        plt.imshow(colored)

    plt.axis('off')
    plt.savefig('all_masks.png')

show_masks(image_rgb, masks)
```

## SAM 2 (नवीनतम संस्करण)

```bash
pip install sam2
```

```python
from sam2.sam2_image_predictor import SAM2ImagePredictor

predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2-hiera-large")

with torch.inference_mode():
    predictor.set_image(image)
    masks, scores, _ = predictor.predict(
        point_coords=points,
        point_labels=labels
    )
```

## बैकग्राउंड हटाएँ

```python
from segment_anything import sam_model_registry, SamPredictor
import cv2
import numpy as np

sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cuda")
predictor = SamPredictor(sam)

def remove_background(image_path, point):
    image = cv2.imread(image_path)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    predictor.set_image(image_rgb)

    masks, scores, _ = predictor.predict(
        point_coords=np.array([point]),
        point_labels=np.array([1]),
        multimask_output=True
    )

    best_mask = masks[np.argmax(scores)]

    # RGBA छवि बनाएं
    result = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA)
    result[:, :, 3] = best_mask.astype(np.uint8) * 255

    return result

# रखने के लिए वस्तु पर क्लिक करें
result = remove_background("photo.jpg", [400, 300])
cv2.imwrite("no_background.png", result)
```

## वस्तु निकालें

```python
def extract_object(image_path, point):
    image = cv2.imread(image_path)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    predictor.set_image(image_rgb)

    masks, scores, _ = predictor.predict(
        point_coords=np.array([point]),
        point_labels=np.array([1]),
        multimask_output=True
    )

    best_mask = masks[np.argmax(scores)]

    # बाउंडिंग बॉक्स प्राप्त करें
    rows = np.any(best_mask, axis=1)
    cols = np.any(best_mask, axis=0)
    y1, y2 = np.where(rows)[0][[0, -1]]
    x1, x2 = np.where(cols)[0][[0, -1]]

    # क्रॉप
    cropped = image[y1:y2+1, x1:x2+1]
    mask_cropped = best_mask[y1:y2+1, x1:x2+1]

    # मास्क लागू करें
    result = cv2.cvtColor(cropped, cv2.COLOR_BGR2BGRA)
    result[:, :, 3] = mask_cropped.astype(np.uint8) * 255

    return result
```

## बैच प्रोसेसिंग

```python
import os
from segment_anything import sam_model_registry, SamAutomaticMaskGenerator
import cv2
import json

sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cuda")

mask_generator = SamAutomaticMaskGenerator(sam)

input_dir = "./images"
output_dir = "./segmented"
os.makedirs(output_dir, exist_ok=True)

for filename in os.listdir(input_dir):
    if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
        image = cv2.imread(os.path.join(input_dir, filename))
        image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        masks = mask_generator.generate(image_rgb)

        # मास्क को JSON के रूप में सहेजें
        mask_data = []
        for i, mask in enumerate(masks):
            mask_data.append({
                'id': i,
                'area': int(mask['area']),
                'bbox': mask['bbox'],
                'score': float(mask['predicted_iou'])
            })

            # व्यक्तिगत मास्क सहेजें
            cv2.imwrite(
                os.path.join(output_dir, f"{filename}_mask_{i}.png"),
                mask['segmentation'].astype(np.uint8) * 255
            )

        with open(os.path.join(output_dir, f"{filename}_masks.json"), 'w') as f:
            json.dump(mask_data, f)
```

## API सर्वर

```python
from fastapi import FastAPI, UploadFile
from fastapi.responses import Response
from segment_anything import sam_model_registry, SamPredictor
import cv2
import numpy as np
import json

app = FastAPI()

sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cuda")
predictor = SamPredictor(sam)

@app.post("/segment")
async def segment(file: UploadFile, x: int, y: int):
    contents = await file.read()
    nparr = np.frombuffer(contents, np.uint8)
    image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    predictor.set_image(image_rgb)

    masks, scores, _ = predictor.predict(
        point_coords=np.array([[x, y]]),
        point_labels=np.array([1]),
        multimask_output=True
    )

    best_mask = masks[np.argmax(scores)]

    _, encoded = cv2.imencode('.png', best_mask.astype(np.uint8) * 255)
    return Response(content=encoded.tobytes(), media_type="image/png")
```

## Stable Diffusion के साथ एकीकरण

इनपेंटिंग के लिए SAM मास्क का उपयोग करें:

```python

# SAM से मास्क जनरेट करें
predictor.set_image(image)
masks, scores, _ = predictor.predict(point_coords=point, point_labels=label)
mask = masks[np.argmax(scores)]

# SD इनपेंटिंग में उपयोग करें
from diffusers import StableDiffusionInpaintPipeline

pipe = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting")
pipe.to("cuda")

result = pipe(
    prompt="a red sports car",
    image=image,
    mask_image=mask
).images[0]
```

## प्रदर्शन

| मॉडल  | छवि आकार  | GPU      | समय    |
| ----- | --------- | -------- | ------ |
| SAM-H | 1024x1024 | RTX 3090 | \~0.5s |
| SAM-L | 1024x1024 | RTX 3090 | \~0.3s |
| SAM-B | 1024x1024 | RTX 3090 | \~0.2s |
| SAM2  | 1024x1024 | RTX 4090 | \~0.3s |

## मेमोरी अनुकूलन

```python

# सीमित VRAM के लिए
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")  # छोटे मॉडल का उपयोग करें

# या स्वचालित जनरेशन पॉइंट्स को कम करें
mask_generator = SamAutomaticMaskGenerator(
    model=sam,
    points_per_side=16,  # 32 से घटाएँ
)
```

## समस्याओं का निवारण

### CUDA मेमोरी समाप्त

* SAM-H के बजाय SAM-B का उपयोग करें
* प्रोसेसिंग से पहले छवि का आकार घटाएँ
* क्लियर कैश: `torch.cuda.empty_cache()`

### खराब सेगमेंटेशन

* अधिक बिंदु जोड़ें (फोरग्राउंड + बैकग्राउंड)
* बेहतर मार्गदर्शन के लिए बॉक्स प्रॉम्प्ट का उपयोग करें
* multimask\_output=True आज़माएँ और सबसे अच्छा चुनें

## लागत अनुमान

सामान्य CLORE.AI मार्केटप्लेस दरें (2024 के अनुसार):

| GPU       | घंटात्मक दर | दैनिक दर | 4-घंटे सत्र |
| --------- | ----------- | -------- | ----------- |
| RTX 3060  | \~$0.03     | \~$0.70  | \~$0.12     |
| RTX 3090  | \~$0.06     | \~$1.50  | \~$0.25     |
| RTX 4090  | \~$0.10     | \~$2.30  | \~$0.40     |
| A100 40GB | \~$0.17     | \~$4.00  | \~$0.70     |
| A100 80GB | \~$0.25     | \~$6.00  | \~$1.00     |

*कीमतें प्रदाता और मांग के अनुसार बदलती हैं। जाँच करें* [*CLORE.AI मार्केटप्लेस*](https://clore.ai/marketplace) *वर्तमान दरों के लिए।*

**पैसे बचाएँ:**

* उपयोग करें **स्पॉट** लचीले वर्कलोड के लिए मार्केट (अक्सर 30-50% सस्ता)
* भुगतान करें **CLORE** टोकन के साथ
* विभिन्न प्रदाताओं के बीच कीमतों की तुलना करें

## अगले कदम

* Stable Diffusion इनपेंटिंग
* [ControlNet गाइड](/guides/guides_v2-hi/image-processing/controlnet-advanced.md)
* [Real-ESRGAN अपस्केलिंग](/guides/guides_v2-hi/image-processing/real-esrgan-upscaling.md)


---

# 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.clore.ai/guides/guides_v2-hi/image-processing/segment-anything.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.
