Examples#

The kit's examples/ folder holds runnable clients and a smoke test. All of them read the server address from the argument or WITHOUTBG_URL (default http://localhost:8000).

FileWhat it does
examples/smoke_test.shChecks a running container end to end, including a Smart Brush edit. Needs bash and python3 only.
examples/python/remove_bg.pyPython (requests): cutout, then a Smart Brush edit with the matte round trip.
examples/node/remove_bg.mjsNode.js 18+ (fetch, no dependencies): same as the Python example.
examples/sample/photo.jpg (two discs) and remove_left.png (a Remove stroke over the left disc).

Try the Smart Brush edit on the sample:

Shell

python examples/python/remove_bg.py examples/sample/photo.jpg --remove examples/sample/remove_left.png
node examples/node/remove_bg.mjs examples/sample/photo.jpg --remove examples/sample/remove_left.png

photo.edited.png shows only the right disc.

docker compose#

The kit's docker-compose.yml: health check on /ready and the settings from Configuration and sizing.

Shell

export WITHOUTBG_IMAGE="<registry>/wbg-pro-selfhost/<your id>:<version>"
docker compose up -d

docker-compose.yml:

YAML

# withoutBG Pro Model Self-Host
#   export WITHOUTBG_IMAGE=<registry>/wbg-pro-selfhost/<your id>:<version>
#   docker compose up -d && examples/smoke_test.sh
services:
  withoutbg:
    image: ${WITHOUTBG_IMAGE:?set WITHOUTBG_IMAGE to the image address and tag we sent you}
    platform: linux/amd64
    restart: unless-stopped
    ports:
      - "8000:8000"  # keep it on a private network; see CONFIG.md "Reverse proxy"
    environment:
      WITHOUTBG_MAX_INFERENCE_SIDE: "1024"  # up to 4096: finer edges on large photos, slower
      # WITHOUTBG_ORT_THREADS: "4"          # cap CPU threads when sharing the server
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/ready')"]
      interval: 10s
      timeout: 5s
      start_period: 120s
      retries: 3

Python#

examples/python/remove_bg.py:

Python

"""withoutBG Pro Model Self-Host: Python client example.

    pip install requests
    python remove_bg.py photo.jpg                       # -> photo.cutout.png
    python remove_bg.py photo.jpg --remove remove.png   # + Smart Brush edit -> photo.edited.png
    WITHOUTBG_URL=http://10.0.0.5:8000 python remove_bg.py photo.jpg

Masks are PNGs the size of the photo: white strokes on black (or transparent).
"""

from __future__ import annotations

import argparse
import base64
import os
import time
from pathlib import Path

import requests

BASE = os.environ.get("WITHOUTBG_URL", "http://localhost:8000").rstrip("/")
TIMEOUT = 180  # one image at a time per container: leave room for the queue


def wait_ready(max_wait: float = 180) -> None:
    """Block until the model is loaded (GET /ready returns 200)."""
    deadline = time.time() + max_wait
    while True:
        try:
            if requests.get(f"{BASE}/ready", timeout=5).status_code == 200:
                return
        except requests.ConnectionError:
            pass
        if time.time() > deadline:
            raise TimeoutError(f"{BASE} not ready after {max_wait:.0f} s")
        time.sleep(3)


def remove_background(photo: bytes, output: str = "cutout") -> bytes:
    """Raw bytes in, PNG out (output: "cutout" or "matte")."""
    r = requests.post(
        f"{BASE}/v1/remove-background",
        params={"output": output},
        data=photo,
        headers={"Content-Type": "application/octet-stream"},
        timeout=TIMEOUT,
    )
    if r.status_code != 200:
        raise RuntimeError(f"{r.status_code}: {r.text}")
    return r.content


def b64(data: bytes) -> str:
    return base64.b64encode(data).decode("ascii")


def smart_brush(
    photo: bytes,
    keep_mask: bytes | None = None,
    remove_mask: bytes | None = None,
    matte: str | None = None,
) -> dict:
    """Base64 endpoint. Returns {"image", "matte", ...}; pass "matte" to the next edit."""
    body = {"image": b64(photo)}
    if keep_mask:
        body["keep_mask"] = b64(keep_mask)
    if remove_mask:
        body["remove_mask"] = b64(remove_mask)
    if matte:
        body["matte"] = matte
    r = requests.post(f"{BASE}/v1/remove-background/base64", json=body, timeout=TIMEOUT)
    if r.status_code != 200:
        raise RuntimeError(f"{r.status_code}: {r.text}")
    return r.json()


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("photo", type=Path)
    ap.add_argument("--keep", type=Path, help="Keep mask PNG")
    ap.add_argument("--remove", type=Path, help="Remove mask PNG")
    args = ap.parse_args()

    wait_ready()
    photo = args.photo.read_bytes()

    cutout = args.photo.with_suffix(".cutout.png")
    cutout.write_bytes(remove_background(photo))
    print(f"wrote {cutout}")

    if args.keep or args.remove:
        first = smart_brush(photo)  # in an editor you already have this matte
        edited = smart_brush(
            photo,
            keep_mask=args.keep.read_bytes() if args.keep else None,
            remove_mask=args.remove.read_bytes() if args.remove else None,
            matte=first["matte"],
        )
        out = args.photo.with_suffix(".edited.png")
        out.write_bytes(base64.b64decode(edited["image"]))
        print(f"wrote {out} ({edited['latencyMs']} ms, route {edited['routeCategory']})")


if __name__ == "__main__":
    main()

Node.js#

examples/node/remove_bg.mjs:

JavaScript

// withoutBG Pro Model Self-Host: Node.js client example (Node 18+, no dependencies).
//
//   node remove_bg.mjs photo.jpg                      # -> photo.cutout.png
//   node remove_bg.mjs photo.jpg --remove remove.png  # + Smart Brush edit -> photo.edited.png
//   WITHOUTBG_URL=http://10.0.0.5:8000 node remove_bg.mjs photo.jpg
//
// Masks are PNGs the size of the photo: white strokes on black (or transparent).
import { readFile, writeFile } from "node:fs/promises";

const BASE = (process.env.WITHOUTBG_URL ?? "http://localhost:8000").replace(/\/$/, "");
const TIMEOUT_MS = 180_000; // one image at a time per container: leave room for the queue

export async function waitReady(maxWaitMs = 180_000) {
  const deadline = Date.now() + maxWaitMs;
  for (;;) {
    try {
      const r = await fetch(`${BASE}/ready`, { signal: AbortSignal.timeout(5000) });
      if (r.ok) return;
    } catch {
      // not up yet
    }
    if (Date.now() > deadline) throw new Error(`${BASE} not ready after ${maxWaitMs / 1000} s`);
    await new Promise((r) => setTimeout(r, 3000));
  }
}

/** Raw bytes in, PNG bytes out. output: "cutout" | "matte". */
export async function removeBackground(photo, output = "cutout") {
  const r = await fetch(`${BASE}/v1/remove-background?output=${output}`, {
    method: "POST",
    headers: { "Content-Type": "application/octet-stream" },
    body: photo,
    signal: AbortSignal.timeout(TIMEOUT_MS),
  });
  if (!r.ok) throw new Error(`${r.status}: ${await r.text()}`);
  return Buffer.from(await r.arrayBuffer());
}

/** Base64 endpoint. Returns {image, matte, ...}; pass `matte` to the next edit. */
export async function smartBrush(photo, { keepMask, removeMask, matte } = {}) {
  const body = { image: photo.toString("base64") };
  if (keepMask) body.keep_mask = keepMask.toString("base64");
  if (removeMask) body.remove_mask = removeMask.toString("base64");
  if (matte) body.matte = matte;
  const r = await fetch(`${BASE}/v1/remove-background/base64`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(TIMEOUT_MS),
  });
  if (!r.ok) throw new Error(`${r.status}: ${await r.text()}`);
  return r.json();
}

async function main() {
  const [photoPath, ...rest] = process.argv.slice(2);
  if (!photoPath) throw new Error("usage: node remove_bg.mjs photo.jpg [--keep k.png] [--remove r.png]");
  const opt = (name) => {
    const i = rest.indexOf(name);
    return i >= 0 ? rest[i + 1] : undefined;
  };
  const stem = photoPath.replace(/\.[^.]+$/, "");

  await waitReady();
  const photo = await readFile(photoPath);
  await writeFile(`${stem}.cutout.png`, await removeBackground(photo));
  console.log(`wrote ${stem}.cutout.png`);

  const keep = opt("--keep");
  const remove = opt("--remove");
  if (keep || remove) {
    const first = await smartBrush(photo); // in an editor you already have this matte
    const edited = await smartBrush(photo, {
      keepMask: keep && (await readFile(keep)),
      removeMask: remove && (await readFile(remove)),
      matte: first.matte,
    });
    await writeFile(`${stem}.edited.png`, Buffer.from(edited.image, "base64"));
    console.log(`wrote ${stem}.edited.png (${edited.latencyMs} ms, route ${edited.routeCategory})`);
  }
}

if (import.meta.url === `file://${process.argv[1]}`) {
  main().catch((e) => {
    console.error(e.message);
    process.exit(1);
  });
}

curl#

Shell

# Cutout
curl -s -H 'Content-Type: image/jpeg' --data-binary @photo.jpg \
  localhost:8000/v1/remove-background -o cutout.png

# Alpha matte
curl -s -H 'Content-Type: image/jpeg' --data-binary @photo.jpg \
  'localhost:8000/v1/remove-background?output=matte' -o matte.png

# Smart Brush: remove what remove.png marks
curl -s -F image=@photo.jpg -F remove_mask=@remove.png \
  localhost:8000/v1/remove-background -o fixed.png

# Base64 in, base64 out
B=$(base64 < photo.jpg | tr -d '\n')
curl -s -H 'Content-Type: application/json' -d "{\"image\": \"$B\"}" \
  localhost:8000/v1/remove-background/base64 | jq -r .image | base64 -d > cutout.png

This page as markdown: /pro-model-self-host/docs/examples.md. Not a customer yet? Pro Model Self-Host.