Skip to content

Latest commit

 

History

History
649 lines (478 loc) · 25.4 KB

File metadata and controls

649 lines (478 loc) · 25.4 KB

useknockout API reference

← Back to the README

Base URL: https://useknockout--api.modal.run

POST /remove

Remove the background from an uploaded image.

Headers

Header Required Description
Authorization Yes Bearer <API_TOKEN>
Content-Type Auto multipart/form-data (set by your client)

Bodymultipart/form-data

Field Type Required Description
file binary Yes Image to process (JPEG, PNG, WebP). Max 25 MB.

Query params

Param Type Default Description
format string png png (default) or webp. Both include alpha.
quality int Compression quality 1–100 for webp. Ignored for png (lossless).
max_dim int Resize so the longest side is ≤ this many px (aspect preserved).
width / height int Exact resize. One alone preserves aspect; both set an exact box.
despill float Knockout Plus. Edge color decontamination strength 0100. Default behavior is full despill; lower to preserve original edge color.
watermark string Knockout Plus. Text watermark, bottom-right, auto-scaled.
watermark_opacity float 0.5 Watermark opacity 0.01.0.
preset string Knockout Plus. Apply a saved preset by name (see /presets). Explicit params override preset values.

Params marked Knockout Plus require a pro-tier key; other callers receive 402. quality, max_dim, width, height are available on all paid tiers.

Responseimage/png or image/webp with a transparent background.

POST /remove-url

Fetch an image from a URL and remove its background.

Headers

Header Required Description
Authorization Yes Bearer <API_TOKEN>
Content-Type Yes application/json

Body — JSON

{
  "url": "https://example.com/image.jpg",
  "format": "png"
}

Response — same as /remove.

POST /psd

Background removal exported as a layered Photoshop .psd — the cutout sits on its own transparent layer ("Cutout"), ready to edit in Photoshop, Affinity, or Photopea.

Paid endpoint. Billed as a $0.10/image add-on (its own meter, independent of your base per-image rate). Included free with Knockout Plus.

Headers

Header Required Description
Authorization Yes Bearer <API_TOKEN> (paid tier)
Content-Type Auto multipart/form-data

Bodymultipart/form-data

Field Type Default Description
file binary Image to process. Max 25 MB.
max_dim / width / height int Resize the output (see /remove).
despill float Knockout Plus. Edge decontamination 0100.
watermark string Knockout Plus. Text watermark.
preset string Knockout Plus. Apply a saved preset.

Responseimage/vnd.adobe.photoshop (a .psd with a transparent cutout layer).

POST /replace-bg

Remove the background and composite the subject onto a new background — solid color or a remote image.

Headers

Header Required Description
Authorization Yes Bearer <API_TOKEN>
Content-Type Auto multipart/form-data (set by your client)

Bodymultipart/form-data

Field Type Required Description
file binary Yes Foreground image to process. Max 25 MB.
bg_color string No (default #FFFFFF) Hex color for the new background. Examples: #000000, #ff5733, #1a73e8.
bg_url string No Remote URL of a background image. Takes precedence over bg_color.
format string No (default png) Output format: png, webp, or jpg (smallest, opaque only).
quality int No Compression quality 1–100 (jpg/webp).
max_dim / width / height int No Resize the output (see /remove).
despill float No Knockout Plus. Edge decontamination 0100.
watermark / watermark_opacity string / float No Knockout Plus. Text watermark + opacity.
preset string No Knockout Plus. Apply a saved preset.

Responseimage/png, image/webp, or image/jpeg with the subject composited onto the new background. Edges are cleaned via closed-form foreground matting (no color spill, no halo).

POST /remove-batch

Remove backgrounds from up to 10 images in one call.

Headers

Header Required Description
Authorization Yes Bearer <API_TOKEN>
Content-Type Auto multipart/form-data

Bodymultipart/form-data with repeated files fields.

Query params

Param Type Default Description
format string png png or webp. Applies to every result.

Response — JSON:

{
  "count": 3,
  "format": "png",
  "results": [
    { "filename": "a.jpg", "success": true, "format": "png", "size_bytes": 124503, "data_base64": "..." },
    { "filename": "b.jpg", "success": true, "format": "png", "size_bytes": 98321, "data_base64": "..." },
    { "filename": "c.jpg", "success": false, "error": "Invalid or unsupported image" }
  ]
}

Each data_base64 decodes to PNG/WebP bytes with a transparent background.

POST /remove-batch-url

Same as /remove-batch but takes a JSON array of remote URLs.

Body — JSON:

{
  "urls": ["https://example.com/a.jpg", "https://example.com/b.jpg"],
  "format": "png"
}

Response — same JSON shape as /remove-batch, with url in place of filename.

POST /mask

Return just the black/white alpha mask as a grayscale PNG/WebP. Useful for chaining into your own compositing pipeline (Photoshop actions, ffmpeg keying, custom workflows).

Field Type Default Description
file binary required Foreground image.
format string png png or webp.

Response — grayscale image (0 = background, 255 = subject).

POST /smart-crop

Auto-crop to the subject's tight bounding box + padding.

Field Type Default Description
file binary required Foreground image.
padding int 24 Pixels of padding around the bbox.
transparent bool true true → cropped cutout with transparent bg. false → cropped region from the original image (bg preserved).
format string png png, webp, or jpg (when transparent=false).

Response — cropped image.

POST /shadow

Composite the subject onto a new background with a configurable drop shadow.

Field Type Default Description
file binary required Foreground image.
bg_color string #FFFFFF Hex color for the new background.
bg_url string Optional remote URL. Takes precedence over bg_color.
shadow_color string #000000 Hex color for the shadow.
shadow_offset_x int 8 Shadow offset in pixels (X).
shadow_offset_y int 12 Shadow offset in pixels (Y).
shadow_blur int 14 Gaussian blur radius in pixels.
shadow_opacity float 0.45 0.0–1.0.
format string png png, webp, or jpg.

POST /sticker

Subject with a thick outline on a transparent background — iMessage / WhatsApp / Telegram sticker style.

Field Type Default Description
file binary required Foreground image.
stroke_color string #FFFFFF Outline color.
stroke_width int 20 Outline width in pixels (capped at 80).
format string png png or webp.

POST /outline

Subject on transparent background with a thin outline.

Field Type Default Description
file binary required Foreground image.
outline_color string #000000 Outline color.
outline_width int 4 Outline width in pixels (capped at 60).
format string png png or webp.

POST /silhouette (v0.8.0)

Two-tone silhouette portrait — subject filled with one solid color, background with another. Apple Music / Spotify avatar style. Use for stylized profile pictures, podcast cover art, anonymized portraits, or branding placeholders.

Field Type Default Description
file binary required Foreground image.
subject_color string #7C3AED Fill color for the subject.
bg_color string #FFFFFF Fill color for the background.
format string png png, webp, or jpg.

POST /inpaint (v0.8.0)

LaMa-based image inpainting — remove objects, people, watermarks, or the subject itself and fill the hole with plausible background. Three modes, auto-detected:

  1. mask field present → user-supplied mask (white = inpaint, black = keep)
  2. x,y,w,h fields present → bbox mode (rectangular region)
  3. Neither → auto-subject mode (BiRefNet derives the subject mask and inverts it — erases the subject, keeps the scene)
Field Type Default Description
file binary required Source image.
mask binary Grayscale mask image (white = inpaint). Resized to match file if needed.
x / y / w / h int Bbox mode: all four required together, must lie inside the image.
dilation int 8 Expand the mask by N pixels (032) before inpainting. Higher values reduce ghost outlines from tight masks.
format string png png, webp, or jpg.

Responses include x-knockout-mode (mask | bbox | auto-subject) and, when the mask covers more than half the image, an x-knockout-warning header (LaMa quality degrades on very large masks). Auto-subject mode returns 422 if no subject is detected.

POST /studio-shot

E-commerce preset: remove background → tight crop → center on solid-color canvas → optional drop shadow → standardized aspect ratio.

Field Type Default Description
file binary required Foreground image.
bg_color string #FFFFFF Canvas color.
aspect string 1:1 W:H format. Examples: 1:1, 4:5, 16:9, 3:2.
padding int 48 Padding around the subject in pixels.
shadow bool true Include a soft drop shadow.
transparent bool false Keep a transparent background. bg_color and shadow are ignored; output is forced to PNG.
enhance bool false Off by default. Set true for a subtle brightness + saturation lift (ecommerce-ready). Leave off for true-to-life color.
enhance_strength float 0.15 Lift amount, 0.00.5. Only applies when enhance=true.
format string jpg png, webp, or jpg.
quality int Compression quality 1–100 (jpg/webp).
max_dim / width / height int Resize the output (see /remove).
despill float Knockout Plus. Edge decontamination 0100.
watermark / watermark_opacity string / float Knockout Plus. Text watermark + opacity.
preset string Knockout Plus. Apply a saved preset.

POST /collage

Product collage: send 2–9 photos, each is background-removed and tight-cropped, then laid out around a main image on a solid canvas. Built for e-commerce hero images (main product + accessories).

Paid tiers only. Billed at N base-image units (each photo is a full model pass — 9 photos = 9 × your per-image price).

Field Type Default Description
files binary[] required 2–9 images, sent as repeated files form fields.
main_index int 0 Which image is the hero (0-based).
main_position string BR Hero anchor: TL, T, TR, L, C, R, BL, B, BR. Hero takes ~65% of the canvas; the rest fill the remaining space in equal cells.
bg_color string #FFFFFF Canvas color.
aspect string 1:1 W:H canvas ratio (between 1:5 and 5:1). Canvas is 1600px on the long side.
padding int 24 Padding inside each cell (px, 0–200).
format string jpg png, webp, or jpg.
quality int Compression quality 1–100 (jpg/webp).
max_dim int Cap the output's longest side (px).
despill float Knockout Plus. Edge decontamination 0100, applied to every cutout.
watermark / watermark_opacity string / float Knockout Plus. Text watermark + opacity.
preset string Knockout Plus. Apply a saved preset (quality, max_dim, despill, watermark).
curl -X POST "https://useknockout--api.modal.run/collage" \
  -H "Authorization: Bearer kno_..." \
  -F "files=@main-product.jpg" \
  -F "files=@accessory-1.jpg" \
  -F "files=@accessory-2.jpg" \
  -F "files=@accessory-3.jpg" \
  -F "main_position=BR" \
  -o collage.jpg

Use cases: marketplace hero images (product + accessories in one shot), listing thumbnails, bundle shots.

POST /video/remove · GET /jobs/{job_id} (v0.11.0)

Video background removal — frame-by-frame BiRefNet with temporal alpha smoothing, async. Submit a clip, get a job_id back immediately, poll for the result.

Paid tiers only. Billed at $0.10 per output second ($0.08 on Knockout Plus — a 10s clip = $1.00 / $0.80), charged on successful completion only. Billing is on output seconds, so speed=2 halves the cost.

Field Type Default Description
file binary required mp4, mov, avi, webm, or mkv. Max 15 seconds, 200MB. Frames above 1920px are downscaled for processing.
format string prores4444 prores4444 — MOV with a real 10-bit alpha channel (drops into DaVinci Resolve, Premiere Pro, After Effects, Final Cut; no green screen). webm — VP9 with alpha, for web. mp4 — H.264, requires an opaque background (no alpha).
bg_color string Composite every frame onto a solid hex color instead of transparency.
bg_image binary Composite every frame onto an uploaded backdrop image. Precedence: bg_image > bg_blur > bg_color > transparent.
bg_blur int 0 1100: composite onto a blurred copy of the source frame (portrait-mode look).
speed float 1.0 0.254.0 output speed multiplier. Audio is tempo-shifted to match.
smoothing int 30 0100 temporal alpha smoothing across frames. Kills matte flicker; lower it for fast-moving subjects.

Processing runs at the source frame rate capped at 30fps. Audio is preserved.

# 1. Submit
curl -X POST "https://useknockout--api.modal.run/video/remove" \
  -H "Authorization: Bearer kno_..." \
  -F "file=@clip.mp4" \
  -F "format=prores4444"
# -> { "job_id": "…", "status": "queued", "seconds": 9.6, "poll": "/jobs/…" }

# 2. Poll until done
curl "https://useknockout--api.modal.run/jobs/JOB_ID" \
  -H "Authorization: Bearer kno_..."
# -> { "status": "done", "progress": 100, "result_url": "https://…" }  (URL valid 1h)

GET /jobs/{job_id} returns status (queued | processing | done | error), progress (0–100), and a signed result_url when done. Jobs are visible only to the key that created them.

Use cases: product videos for marketplace listings, talking-head cutouts, social clips on brand backgrounds, editor pipelines needing true alpha.

POST /presets · GET /presets · DELETE /presets/{name}

Knockout Plus. Save reusable output configs and apply them by name with preset=<name> on /remove, /replace-bg, /studio-shot, and /psd. A preset sets defaults; any explicit param on the request overrides it.

  • POST /presets — create/update. JSON body { "name": "web-thumb", "config": { "max_dim": 800, "quality": 75, "despill": 60, "watermark": "© Brand" } }. Config keys: quality, max_dim, width, height, despill, watermark (unknown keys dropped).
  • GET /presets — list your presets.
  • DELETE /presets/{name} — delete one.

Presets are per-user (tied to your API key's account). Requires a pro-tier key.

POST /compare

Before/after side-by-side preview — original on the left, transparent cutout (on a checkerboard) on the right. Great for marketing / social media screenshots.

Field Type Default Description
file binary required Foreground image.
format string png png or webp.

POST /headshot (v0.4.0)

Studio-quality professional headshot — background removed, neutral studio backdrop, optional soft shadow, smart crop to bust framing. One call.

Field Type Default Description
file binary required Source portrait.
bg_color string #f5f5f5 Studio backdrop hex.
add_shadow bool true Soft drop shadow.
crop string bust bust, head, or full.
format string png png, webp, or jpg.

POST /preview (v0.4.0)

Cheap, fast low-res preview — 512px max, watermark optional. Use for thumbnail UI before user pays for full-res. Returns in ~1.5s.

Field Type Default Description
file binary required Source image.
max_size int 512 Max edge length.
watermark bool false Add useknockout watermark.

POST /estimate (v0.4.0)

Returns expected processing time + output size without running the model. Use to show users "this'll take ~3s, ~1.2 MB" before they hit submit.

curl -X POST "https://useknockout--api.modal.run/estimate" \
  -H "Content-Type: application/json" \
  -d '{"width": 2048, "height": 1536, "endpoint": "remove"}'

Response: {"estimated_seconds": 2.4, "estimated_output_kb": 1180, "warm": true}

GET /stats (v0.4.0)

Public stats — total images processed, last-24h count, last-7d trend. Powered by Modal Dict cross-container counter. No auth required.

curl https://useknockout--api.modal.run/stats

POST /upscale (v0.6.0, backend default changed v0.9.0)

Real-ESRGAN / Swin2SR x2/x4 super-resolution. Takes blurry/small images, outputs 2x or 4x larger with AI-restored detail. Not pixel stretching — invents plausible texture.

v0.9.0 — default backend is Real-ESRGAN x4plus: restores and invents plausible detail, best "wow" on low-res or degraded photos, and faster (single pass, no tiling). Swin2SR (SwinV2 Transformer) remains available via model=swin2sr: faithful, no invented detail — prefer it for accuracy-sensitive product or archival work.

# default — Real-ESRGAN (best on low-res / degraded photos)
curl -X POST "https://useknockout--api.modal.run/upscale" \
  -H "Authorization: Bearer $KNOCKOUT_TOKEN" \
  -F "file=@small.jpg" \
  -F "scale=4" \
  -o upscaled.png

# Swin2SR (faithful — best for product / archival accuracy)
curl -X POST "https://useknockout--api.modal.run/upscale" \
  -H "Authorization: Bearer $KNOCKOUT_TOKEN" \
  -F "file=@product.jpg" \
  -F "scale=4" \
  -F "model=swin2sr" \
  -o upscaled.png
Field Type Default Description
file binary required Source image.
scale int 4 2 or 4.
model string realesrgan realesrgan (default) restores detail — best on low-res/degraded photos. swin2sr is faithful (no invented detail) for accuracy-sensitive work.
face_enhance bool false Route through GFPGAN for facial detail. Implies Real-ESRGAN backend.
format string png png, webp, or jpg.

Use cases: restore old photos, enlarge product shots, fix low-res screenshots, upscale AI-generated thumbnails.

POST /face-restore (v0.5.0)

GFPGAN v1.4 face restoration. Detects faces, restores blurred/compressed/damaged ones while preserving identity. Background also upscaled via Real-ESRGAN. Multi-face safe.

curl -X POST "https://useknockout--api.modal.run/face-restore" \
  -H "Authorization: Bearer $KNOCKOUT_TOKEN" \
  -F "file=@blurry-portrait.jpg" \
  -o restored.png
Field Type Default Description
file binary required Source image with one or more faces.
format string png png, webp, or jpg.

Use cases: old family photos, Zoom screenshots, dating app pics, restore CCTV stills.

POST /colorize (v0.8.0)

DDColor colorization for black-and-white or grayscale photos. ConvNeXt-Large backbone predicts color in LAB space — single feed-forward pass, ~500ms warm. Color inputs are accepted too (treated as grayscale internally).

curl -X POST "https://useknockout--api.modal.run/colorize" \
  -H "Authorization: Bearer $KNOCKOUT_TOKEN" \
  -F "file=@bw-photo.jpg" \
  -o colorized.png
Field Type Default Description
file binary required Source image.
format string png png, webp, or jpg.

Use cases: restore old family photos, colorize archival/historical images, stylize scans.

GET /health

Returns {"status":"ok","model":"ZhengPeng7/BiRefNet"}. No auth required.

GET /docs

Interactive OpenAPI (Swagger) UI.

Errors

Code Meaning
400 Invalid image, missing field, malformed URL, invalid hex color, or batch > 10 items
401 Missing Authorization header
402 Tier limit: free tier hitting a paid endpoint, free monthly quota (10) exhausted, non-Plus key using a Plus param, or demo key limits
403 Invalid bearer token
404 Unknown job_id on GET /jobs/{job_id}
413 Image exceeds 25 MB limit (200 MB for video)
422 /inpaint auto-subject mode found no subject
500 Server error (check dashboard logs)

Edge quality

All endpoints apply closed-form foreground matting (via pymatting) after mask prediction. This estimates pure foreground color at soft edges, eliminating color spill from the original background. Result: no halos, no fringing, even on backgrounds that differ sharply from the subject.


Client examples

Python

import os
import requests

URL = "https://useknockout--api.modal.run/remove"
TOKEN = os.environ["KNOCKOUT_TOKEN"]  # get yours at useknockout.com/signin

with open("input.jpg", "rb") as f:
    resp = requests.post(
        URL,
        headers={"Authorization": f"Bearer {TOKEN}"},
        files={"file": f},
    )
resp.raise_for_status()

with open("output.png", "wb") as f:
    f.write(resp.content)

Node.js SDK (recommended)

npm i @useknockout/node
import { writeFile } from "node:fs/promises";
import { Knockout } from "@useknockout/node";

const client = new Knockout({ token: process.env.KNOCKOUT_TOKEN! });

// 1. Remove background → transparent PNG
const png = await client.remove({ file: "./input.jpg" });
await writeFile("out.png", png);

// 2. Replace background with a color
const jpg = await client.replaceBackground({
  file: "./input.jpg",
  bgColor: "#FF5733",
  format: "jpg",
});
await writeFile("out.jpg", jpg);

// 3. Replace background with a remote image
const composed = await client.replaceBackground({
  file: "./input.jpg",
  bgUrl: "https://example.com/mountains.jpg",
});

// 4. Batch — process 10 URLs in one call
const batch = await client.removeBatchUrl({
  urls: ["https://example.com/a.jpg", "https://example.com/b.jpg"],
});
for (const r of batch.results) {
  if (r.success) await writeFile(`out-${r.url}.png`, Buffer.from(r.data_base64!, "base64"));
}

Node.js (raw fetch, no SDK)

import { readFile, writeFile } from "node:fs/promises";

const URL = "https://useknockout--api.modal.run/remove";
const TOKEN = process.env.KNOCKOUT_TOKEN;

const buf = await readFile("input.jpg");
const form = new FormData();
form.set("file", new Blob([buf]), "input.jpg");

const res = await fetch(URL, {
  method: "POST",
  headers: { Authorization: `Bearer ${TOKEN}` },
  body: form,
});
if (!res.ok) throw new Error(await res.text());

await writeFile("output.png", Buffer.from(await res.arrayBuffer()));

TypeScript (browser / Next.js)

export async function removeBackground(file: File, token: string) {
  const form = new FormData();
  form.append("file", file);

  const res = await fetch("https://useknockout--api.modal.run/remove", {
    method: "POST",
    headers: { Authorization: `Bearer ${token}` },
    body: form,
  });

  if (!res.ok) throw new Error(`knockout error: ${res.status}`);
  return await res.blob(); // PNG with alpha
}

Go

package main

import (
    "bytes"
    "io"
    "mime/multipart"
    "net/http"
    "os"
)

func removeBG(path, token string) ([]byte, error) {
    f, err := os.Open(path)
    if err != nil { return nil, err }
    defer f.Close()

    body := &bytes.Buffer{}
    w := multipart.NewWriter(body)
    part, _ := w.CreateFormFile("file", path)
    io.Copy(part, f)
    w.Close()

    req, _ := http.NewRequest("POST",
        "https://useknockout--api.modal.run/remove", body)
    req.Header.Set("Authorization", "Bearer "+token)
    req.Header.Set("Content-Type", w.FormDataContentType())

    resp, err := http.DefaultClient.Do(req)
    if err != nil { return nil, err }
    defer resp.Body.Close()
    return io.ReadAll(resp.Body)
}

cURL — WebP output (smaller files)

curl -X POST "https://useknockout--api.modal.run/remove?format=webp" \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@input.jpg" \
  -o output.webp