# Remove image backgrounds into transparent cutouts

> OpenGen exposes foreground segmentation and alpha cutout extraction under the dedicated background-remove operation. Upload a private source image via POST /v1/assets, inspect exact constraints for bria/remove-background (alpha-capable PNG or WebP output only, with no prompt field), verify route availability and published per-image rates via POST /v1/pricing/estimate, and submit with a persisted Idempotency-Key once an executable route is configured.

## Agent Prompt

```text
Walk me through a background-remove workflow on OpenGen (https://opengen.dev):
1. Discover background removal models with GET https://opengen.dev/v1/models?operation=background-remove (or MCP find_models with operation="background-remove").
2. Inspect exact schema limits and published pricing via GET https://opengen.dev/v1/models/bria/remove-background?operation=background-remove (or MCP get_model with id="bria/remove-background", operation="background-remove"). Note that prompt is NOT accepted and outputFormat must be "png" or "webp".
3. Upload the single private source image via POST https://opengen.dev/v1/assets (or MCP upload_asset) and confirm state="ready".
4. Run POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) to inspect workspaceEligibility and published per-image rates. Stop and report if routes are documented/comparison-only on the current gateway.
5. Only when an executable route is eligible and I approve the spend cap, submit once with a persisted Idempotency-Key via POST https://opengen.dev/v1/generations or MCP generate.
```

OpenGen models transparent foreground segmentation under the dedicated `background-remove` operation. Because background removal does not use text prompts or opaque JPEG outputs, the canonical schema enforces those guardrails before any credit reservation or upstream call occurs.

> [!NOTE]
> Check route executability before promising live dispatch. In the current catalog snapshot, `fal-undisclosed/bria-remove-background` and `replicate-undisclosed/bria-remove-background` carry `status: "documented"` with no active execution adapter (comparison-only until enabled on your gateway). Also note the licensing distinction: BRIA RMBG 2.0 open weights carry a `CC BY-NC 4.0` non-commercial license, while partner API routes include commercial usage under each provider's terms.

## 1. Inspect `bria/remove-background` schema and pricing

[BRIA RMBG 2.0](/bria/remove-background) (`bria/remove-background`) is documented across fal (`$0.018` per output image) and Replicate. Inspect its live schema and routes in one call:

```bash tab="cURL"
curl --fail-with-body \
  "https://opengen.dev/v1/models?operation=background-remove"

curl --fail-with-body \
  "https://opengen.dev/v1/models/bria/remove-background?operation=background-remove"
```

```ts tab="TypeScript"
const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';
const detail = await fetch(
  `${origin}/v1/models/bria/remove-background?operation=background-remove`,
).then((r) => r.json());
console.log(detail.model.generationProfiles[0], detail.pricing);
```

```python tab="Python"
import os
import httpx

origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
with httpx.Client(timeout=30.0) as client:
    detail = client.get(
        f"{origin}/v1/models/bria/remove-background",
        params={"operation": "background-remove"},
    ).raise_for_status().json()
    print(detail["model"]["generationProfiles"][0], detail["pricing"])
```

```json tab="MCP"
{
  "tool": "get_model",
  "arguments": {
    "id": "bria/remove-background",
    "operation": "background-remove"
  }
}
```

```bash tab="CLI"
opengen catalog search --operation background-remove
opengen catalog get bria/remove-background
opengen pricing --model bria/remove-background --operation background-remove
```

### Valid `bria/remove-background` fields

| Field          | Required | Allowed values                                                                       |
| -------------- | -------- | ------------------------------------------------------------------------------------ |
| `references`   | Yes      | Exactly `1` image reference (`{ "type": "image", "asset": { "assetKey": "..." } }`). |
| `outputFormat` | Optional | Alpha-capable format only: `png` (default) or `webp`.                                |

`prompt`, `resolution`, `aspectRatio`, `mask`, and `outputFormat: "jpeg"` are rejected with `400 invalid_generation`.

## 2. Upload your private source image

Upload a workspace-private image via `POST /v1/assets` or reuse an earlier OpenGen generation output with `{ "source": "job_output", "sourceJobId": "<job-uuid>", "outputIndex": 0 }`.

```bash tab="cURL"
curl --fail-with-body \
  -X POST "https://opengen.dev/v1/assets" \
  -H "Authorization: Bearer $OPENGEN_API_KEY" \
  -H "Idempotency-Key: bgrem-src-$(uuidgen | tr '[:upper:]' '[:lower:]')" \
  -F "file=@./sneaker-photo.jpg;type=image/jpeg"
```

```ts tab="TypeScript"
import { readFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';

const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';
const form = new FormData();
form.append(
  'file',
  new Blob([await readFile('./sneaker-photo.jpg')], { type: 'image/jpeg' }),
  'sneaker-photo.jpg',
);

const asset = await fetch(`${origin}/v1/assets`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`,
    'Idempotency-Key': `bgrem-src-${randomUUID()}`,
  },
  body: form,
}).then((r) => r.json());
console.log(asset.assetKey, asset.state);
```

```python tab="Python"
import os
import uuid
import httpx

origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
with open("sneaker-photo.jpg", "rb") as fh, httpx.Client(timeout=60.0) as client:
    asset = client.post(
        f"{origin}/v1/assets",
        headers={
            "Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}",
            "Idempotency-Key": f"bgrem-src-{uuid.uuid4()}",
        },
        files={"file": ("sneaker-photo.jpg", fh, "image/jpeg")},
    ).raise_for_status().json()
    print(asset["assetKey"], asset["state"])
```

```json tab="MCP"
{
  "tool": "upload_asset",
  "arguments": {
    "source": "url",
    "url": "https://assets.example.com/catalog/sneaker-photo.jpg",
    "type": "image",
    "idempotencyKey": "bgrem-import-001"
  }
}
```

```bash tab="CLI"
opengen upload /absolute/path/sneaker-photo.jpg --media-type image/jpeg
```

## 3. Estimate cost and route eligibility before submitting

Notice that `input` contains **only** `references` and `outputFormat`—do not include `prompt`. Run `POST /v1/pricing/estimate` first to review published pricing and `workspaceEligibility`.

```bash tab="cURL"
set -eu
umask 077
if [ -e bg-remove-submission.key ]; then
  echo "Existing bg-remove-submission.key found; recover read-only via GET /v1/generations/lookup before replacing bg-remove-request.json." >&2
  exit 1
fi
rm -f bg-remove-request.json
cat <<'JSON' > bg-remove-request.json
{
  "modelId": "bria/remove-background",
  "operation": "background-remove",
  "input": {
    "references": [
      {
        "type": "image",
        "asset": {
          "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.jpg"
        }
      }
    ],
    "outputFormat": "png"
  },
  "routeId": "fal-undisclosed/bria-remove-background",
  "billing": "managed",
  "maxCostMicros": 50000
}
JSON
chmod 600 bg-remove-request.json

# Dry-run estimate only (review selectedRouteId, recommendedMaxCostMicros, and workspaceEligibility)
curl --fail-with-body \
  -X POST "https://opengen.dev/v1/pricing/estimate" \
  -H "Authorization: Bearer $OPENGEN_API_KEY" \
  -H "Content-Type: application/json" \
  --data @bg-remove-request.json
```

```json tab="MCP"
{
  "tool": "estimate_cost",
  "arguments": {
    "modelId": "bria/remove-background",
    "operation": "background-remove",
    "input": {
      "references": [
        {
          "type": "image",
          "asset": {
            "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.jpg"
          }
        }
      ],
      "outputFormat": "png"
    },
    "routeId": "fal-undisclosed/bria-remove-background",
    "billing": "managed",
    "maxCostMicros": 50000
  }
}
```

```bash tab="CLI"
opengen pricing estimate --input bg-remove-request.json
```

### Submit once after reviewing the estimate

Run this step only after reviewing the estimate output above and confirming an executable route is eligible (`selectedRouteId != null`, `executableCandidateCount > 0`, `blockers: []`) and confirming `maxCostMicros`.

```bash tab="cURL"
set -eu
umask 077
if [ -e bg-remove-submission.key ]; then
  echo "Existing bg-remove-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2
  exit 1
fi
RAW_UUID="$(uuidgen)"
[ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; }
IDEMPOTENCY_KEY="bgrem-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')"
(set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > bg-remove-submission.key)

curl --fail-with-body \
  -X POST "https://opengen.dev/v1/generations" \
  -H "Authorization: Bearer $OPENGEN_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
  -H "Prefer: wait=20" \
  --data @bg-remove-request.json > bg-remove-receipt.json
```

```ts tab="TypeScript"
import { randomUUID } from 'node:crypto';
import { writeFile } from 'node:fs/promises';

const bgPayload = {
  modelId: 'bria/remove-background',
  operation: 'background-remove',
  input: {
    references: [{ type: 'image', asset: { assetKey: asset.assetKey } }],
    outputFormat: 'png',
  },
  routeId: 'fal-undisclosed/bria-remove-background',
  billing: 'managed',
  maxCostMicros: 50000,
} as const;

const headers = {
  Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`,
  'Content-Type': 'application/json',
};

const estRes = await fetch(`${origin}/v1/pricing/estimate`, {
  method: 'POST',
  headers,
  body: JSON.stringify(bgPayload),
});
if (!estRes.ok) throw new Error(`Estimate failed (${estRes.status}): ${await estRes.text()}`);
const estimate = await estRes.json();
console.log('Review estimate before submitting:', estimate);

const eligibility = estimate.workspaceEligibility;
const canSubmit = Boolean(
  estimate.selectedRouteId &&
  eligibility?.policyAllowed === true &&
  eligibility.hasActiveBillingHold === false &&
  eligibility.executableCandidateCount > 0 &&
  (eligibility.billingMode === 'byok' || eligibility.sufficientBalance === true) &&
  Array.isArray(eligibility.blockers) &&
  eligibility.blockers.length === 0,
);
if (canSubmit && process.env.CONFIRM_SUBMIT === '1') {
  const idempotencyKey = `bgrem-${randomUUID()}`;
  await writeFile(
    'bg-remove-submission.json',
    JSON.stringify({ idempotencyKey, payload: bgPayload }, null, 2),
    { mode: 0o600, flag: 'wx' },
  );
  const genRes = await fetch(`${origin}/v1/generations`, {
    method: 'POST',
    headers: { ...headers, 'Idempotency-Key': idempotencyKey, Prefer: 'wait=20' },
    body: JSON.stringify(bgPayload),
  });
  if (!genRes.ok) throw new Error(`Generation failed (${genRes.status}): ${await genRes.text()}`);
  const job = await genRes.json();
  console.log(job.id, job.status);
}
```

```python tab="Python"
import json
import os
import uuid
import httpx

origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
bg_payload = {
    "modelId": "bria/remove-background",
    "operation": "background-remove",
    "input": {
        "references": [{"type": "image", "asset": {"assetKey": asset["assetKey"]}}],
        "outputFormat": "png",
    },
    "routeId": "fal-undisclosed/bria-remove-background",
    "billing": "managed",
    "maxCostMicros": 50000,
}

with httpx.Client(timeout=45.0) as client:
    auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"}
    estimate = client.post(f"{origin}/v1/pricing/estimate", headers=auth, json=bg_payload).raise_for_status().json()
    print("Review estimate before submitting:", estimate)
    eligibility = estimate.get("workspaceEligibility") or {}
    can_submit = (
        bool(estimate.get("selectedRouteId"))
        and eligibility.get("policyAllowed") is True
        and eligibility.get("hasActiveBillingHold") is False
        and eligibility.get("executableCandidateCount", 0) > 0
        and (eligibility.get("billingMode") == "byok" or eligibility.get("sufficientBalance") is True)
        and eligibility.get("blockers") == []
    )
    if can_submit and os.environ.get("CONFIRM_SUBMIT") == "1":
        idempotency_key = f"bgrem-{uuid.uuid4()}"
        fd = os.open("bg-remove-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump({"idempotencyKey": idempotency_key, "payload": bg_payload}, handle, indent=2)
        job = client.post(
            f"{origin}/v1/generations",
            headers={**auth, "Idempotency-Key": idempotency_key, "Prefer": "wait=20"},
            json=bg_payload,
        ).raise_for_status().json()
        print(job["id"], job["status"])
```

```json tab="MCP"
{
  "tool": "generate",
  "arguments": {
    "idempotencyKey": "bgrem-example-001",
    "modelId": "bria/remove-background",
    "operation": "background-remove",
    "input": {
      "references": [
        {
          "type": "image",
          "asset": {
            "assetKey": "inputs/YOUR_WORKSPACE/RETURNED_IMAGE_UUID.jpg"
          }
        }
      ],
      "outputFormat": "png"
    },
    "routeId": "fal-undisclosed/bria-remove-background",
    "billing": "managed",
    "maxCostMicros": 50000,
    "waitMs": 20000
  }
}
```

```bash tab="CLI"
set -eu
umask 077
if [ -e bg-remove-submission.key ]; then
  echo "Existing bg-remove-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat bg-remove-submission.key)\"' before creating a new submission." >&2
  exit 1
fi
RAW_UUID="$(uuidgen)"
[ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; }
IDEMPOTENCY_KEY="bgrem-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')"
(set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > bg-remove-submission.key)
opengen generate --input bg-remove-request.json --idempotency-key "$IDEMPOTENCY_KEY" --wait 20 > bg-remove-receipt.json
```

> [!TIP]
> Need an executable transparent-background image workflow today? [GPT Image 2](/openai/gpt-image-2) (`image-edit`) supports `background: "transparent"` with `outputFormat: "png"` through its active official OpenAI adapter (note that `openai-undisclosed/openai-gpt-image-2` is live-verified for `text-to-image` at `1K`, while `image-edit` and transparent cutouts remain `documented`)—see [Image Editing](/docs/guides/image-edit).

## Next steps

- Composite your cutout into a new scene with [Image Editing](/docs/guides/image-edit).
- Use the cutout as a character reference in [Reference to Video](/docs/guides/reference-to-video).

## Supported Models

Live catalog variants supporting `background-remove` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`).

| Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema |
| --- | --- | --- | --- | --- | --- | --- |
| [BRIA RMBG 2.0](https://opengen.dev/bria/remove-background#variant-bria-remove-background) | `bria/remove-background` | BRIA AI | 2 | $0.018 / image | Open weights | `GET /v1/models/bria/remove-background?operation=background-remove` |
