# Segment Anything Model 2 · Image API

> اشیا را در یک تصویر منفرد از روی اعلان‌های نقطه‌ای یا کادری بخش‌بندی می‌کند و ماسک یا تصویر ماسک‌شده را برمی‌گرداند

یک تصویر را با SAM 2 و با استفاده از اعلان‌های نقطه‌ای (`prompts`) یا مختصات کادر (`box_prompts`) بخش‌بندی می‌کند. `apply_mask` را روی true تنظیم کنید تا ماسک روی تصویر اعمال شود، نه اینکه فقط خود ماسک برگردد. خروجی را می‌توان به‌صورت jpeg، png یا webp ذخیره کرد؛ png پیش‌فرض است. هر درخواست یک URL تصویر می‌گیرد.

- Model id: `sam2/image`
- Made by: Meta
- Category: Image Editing
- Output: image
- Estimated price per run: $0.002 / run (cheapest run $0.002 (2 API credits))
- Run: `POST https://api.doitong.com/v1/run/sam2/image`
- Quote: `POST https://api.doitong.com/v1/quote/sam2/image`
- Docs page: https://doitong.com/fa/developers/models/sam2/image

## Pricing

Price: **$0.002 / run**. Estimated from the typical cost of one run. The quote is exactly what the run charges.

The full example input below costs $0.002 = 2 API credits (1 request × 2 API credits).

Prices are the upstream price in USD, paid from the API balance in API credits (1000 API credits = 1 USD). `POST https://api.doitong.com/v1/quote/sam2/image` with the same JSON body returns the exact price for that input; the quote is exactly what a run charges. Invalid input is never charged and failed or canceled requests are refunded automatically.

## Input parameters

Send either the canonical name or the native field name (not both). Canonical names are the same across models.

| Parameter | Canonical name | Type | Required | Default | Allowed values / range | Description |
|---|---|---|---|---|---|---|
| `image_url` | `image` | string (image URL) | yes |  |  | URL تصویر برای قطعه‌بندی. |
| `prompts` |  | array of object {x, y, label, frame_index} | no | `[]` |  | پرامپت‌های مورد استفاده برای بخش‌بندی تصویر. |
| `prompts[].x` |  | integer | no | `305` |  | موقعیت پرامپت روی محور X. |
| `prompts[].y` |  | integer | no | `350` |  | موقعیت پرامپت روی محور Y. |
| `prompts[].label` |  | enum (integer) | no | `1` | `0`, `1` | برچسب پرامپت: 1 نشان‌دهندهٔ پیش‌زمینه و 0 نشان‌دهندهٔ پس‌زمینه است. |
| `prompts[].frame_index` |  | integer | no | `0` |  | شاخص شناسایی‌کننده فریم برای تعامل. |
| `box_prompts` |  | array of object {x_min, y_min, x_max, y_max, frame_index} | no | `[]` |  | مختصات مرز کادر. |
| `box_prompts[].x_min` |  | integer | no | `0` |  | کمینهٔ مختصات x برای کادر. |
| `box_prompts[].y_min` |  | integer | no | `0` |  | کمینهٔ مختصات y برای کادر. |
| `box_prompts[].x_max` |  | integer | no | `0` |  | بیشینهٔ مختصات x برای پرامپت. |
| `box_prompts[].y_max` |  | integer | no | `0` |  | بیشینهٔ مختصات y برای پرامپت. |
| `box_prompts[].frame_index` |  | integer | no | `0` |  | شاخص شناسایی‌کننده فریم برای تعامل. |
| `apply_mask` |  | boolean | no | `false` |  | کنترل می‌کند که ماسک روی تصویر اعمال شود یا نه. |
| `output_format` |  | enum (string) | no | `png` | `jpeg`, `png`, `webp` | قالب فایل تصویر نهایی. |

File parameters (`image`) take a public `https://` URL, a `data:` URI up to 10 MB, or the `file_url` of an upload from `POST /files`.

## Example input

Required parameters only:

```json
{
  "image": "https://content.doitong.com/images/showcase/v3/gen_fox_cartoon.jpg"
}
```

A fuller example:

```json
{
  "image_url": "https://content.doitong.com/images/showcase/v3/gen_fox_cartoon.jpg"
}
```

## Run it

Set `DOITONG_API_KEY` to a key from https://doitong.com/developers/dashboard#keys. `?wait=20` returns the finished request in the same call when it is ready within 20 seconds; otherwise poll `GET /requests/{id}` (it also accepts `?wait=`), or pass `webhook_url`.

### curl

```bash
# Run the model; wait up to 20 s for the finished result in the same call
curl -X POST "https://api.doitong.com/v1/run/sam2/image?wait=20" \
  -H "Authorization: Bearer $DOITONG_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "image_url": "https://content.doitong.com/images/showcase/v3/gen_fox_cartoon.jpg"
  }'

# Still "queued" or "running"? Poll with the id from the response:
curl "https://api.doitong.com/v1/requests/REQUEST_ID?wait=20" \
  -H "Authorization: Bearer $DOITONG_API_KEY"
```

### JavaScript

```javascript
const API = "https://api.doitong.com/v1";
const headers = {
  "Authorization": "Bearer " + process.env.DOITONG_API_KEY,
  "Content-Type": "application/json",
};

// Run the model; wait up to 20 s for the finished result in the same call
let res = await fetch(API + "/run/sam2/image?wait=20", {
  method: "POST",
  headers,
  body: JSON.stringify({
    "image_url": "https://content.doitong.com/images/showcase/v3/gen_fox_cartoon.jpg"
  }),
});
let request = await res.json();
if (!res.ok) throw new Error(request.error.code + ": " + request.error.message);

// Not finished yet: long-poll until it is
while (request.status === "queued" || request.status === "running") {
  res = await fetch(API + "/requests/" + request.id + "?wait=20", { headers });
  request = await res.json();
}
if (request.status !== "succeeded") throw new Error(JSON.stringify(request.error));
console.log(request.outputs.map((o) => o.url), request.cost.credits + " API credits ($" + request.cost.usd + ")");
```

### Python

```python
import os
import requests

API = "https://api.doitong.com/v1"
headers = {"Authorization": "Bearer " + os.environ["DOITONG_API_KEY"]}

payload = {
    "image_url": "https://content.doitong.com/images/showcase/v3/gen_fox_cartoon.jpg",
}

# Run the model; wait up to 20 s for the finished result in the same call
r = requests.post(API + "/run/sam2/image", params={"wait": 20}, json=payload, headers=headers)
request = r.json()
if not r.ok:
    raise RuntimeError(request["error"]["code"] + ": " + request["error"]["message"])

# Not finished yet: long-poll until it is
while request["status"] in ("queued", "running"):
    request = requests.get(API + "/requests/" + request["id"], params={"wait": 20}, headers=headers).json()
if request["status"] != "succeeded":
    raise RuntimeError(request["error"])
print([o["url"] for o in request["outputs"]], request["cost"]["credits"], "API credits", "$" + request["cost"]["usd"])
```

### MCP

The MCP server at `https://api.doitong.com/v1/mcp` exposes the tools `search_models`, `get_model`, `quote`, `run`, `get_request`, `cancel_request`, `list_requests`, `create_upload` and `get_account`. A `run` call for this model:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "run",
    "arguments": {
      "model_id": "sam2/image",
      "input": {
        "image_url": "https://content.doitong.com/images/showcase/v3/gen_fox_cartoon.jpg"
      },
      "wait_seconds": 20
    }
  }
}
```

## Response

Every call returns a request object. `status` is one of `queued`, `running`, `succeeded`, `failed`, `canceled`. `outputs` lists the generated files with URLs on our storage (kept forever, or 7 days with `?storage=temporary`; `storage` says which); `output` is the model's own result object with the same URLs.

```json
{
  "id": "req_8k2m4q7x1z9c3v5b6n0p2r4t",
  "object": "request",
  "model": "sam2/image",
  "status": "succeeded",
  "created_at": "2026-10-20T12:00:00Z",
  "started_at": "2026-10-20T12:00:02Z",
  "completed_at": "2026-10-20T12:00:09Z",
  "queue_position": null,
  "cost": {
    "credits": 2,
    "usd": "0.002",
    "charged": 2,
    "refunded": 0
  },
  "input": {
    "image_url": "https://content.doitong.com/images/showcase/v3/gen_fox_cartoon.jpg"
  },
  "output": {
    "image": {
      "url": "https://content.doitong.com/dev-api/2026/10/20/req_8k2m4q7x1z9c3v5b6n0p2r4t/0-output.jpeg",
      "content_type": "image/jpeg",
      "file_name": "0-output.jpeg",
      "file_size": 1843200,
      "width": 1024,
      "height": 768
    }
  },
  "outputs": [
    {
      "type": "image",
      "url": "https://content.doitong.com/dev-api/2026/10/20/req_8k2m4q7x1z9c3v5b6n0p2r4t/0-output.jpeg",
      "content_type": "image/jpeg",
      "file_size": 1843200,
      "width": 1024,
      "height": 768,
      "stored": true
    }
  ],
  "error": null,
  "metrics": {
    "inference_seconds": 6.8
  },
  "urls": {
    "self": "https://api.doitong.com/v1/requests/req_8k2m4q7x1z9c3v5b6n0p2r4t",
    "cancel": "https://api.doitong.com/v1/requests/req_8k2m4q7x1z9c3v5b6n0p2r4t/cancel"
  }
}
```

### Output fields (`output`)

| Field | Type | Description |
|---|---|---|
| `image` | object {url, content_type, file_name, file_size, width, height} | تصویر با بخش‌بندی اعمال‌شده. |

## Related models

- [Segment Anything Model 2 · Auto Segment](https://doitong.com/developers/models/sam2/auto-segment.md) (`sam2/auto-segment`): $0.014 / run
- [Segment Anything Model 2 · Video](https://doitong.com/developers/models/sam2/video.md) (`sam2/video`): $0.001111 / second of processing time
- [FLUX.1 Kontext \[pro\]](https://doitong.com/developers/models/flux-pro/kontext.md) (`flux-pro/kontext`): $0.04 / image
- [GPT Image 2.5 Edit](https://doitong.com/developers/models/openai/gpt-image-2.5/flare/edit.md) (`openai/gpt-image-2.5/flare/edit`): from $0.12 / image
- [Nano Banana 2 Edit](https://doitong.com/developers/models/nano-banana-2/edit.md) (`nano-banana-2/edit`): from $0.06 / image
- [Nano Banana Pro Edit](https://doitong.com/developers/models/nano-banana-pro/edit.md) (`nano-banana-pro/edit`): from $0.15 / image
- [Qwen Image 3 Edit](https://doitong.com/developers/models/alibaba/qwen-image-3/edit.md) (`alibaba/qwen-image-3/edit`): from $0.04 / image
- [Seedream 5.0 Pro Edit](https://doitong.com/developers/models/bytedance/seedream/v5/pro/edit.md) (`bytedance/seedream/v5/pro/edit`): from $0.0675 / run of output image

## Links

- HTML page: https://doitong.com/developers/models/sam2/image
- All models and guides for AI agents: https://doitong.com/developers/llms.txt
- OpenAPI 3.1 with this model's typed request body: https://doitong.com/developers/openapi.json?model=sam2/image
- Errors: https://doitong.com/developers/docs/errors
- Model details as JSON: https://api.doitong.com/v1/models/sam2/image
