How to remove image backgrounds in Python (2027 guide)

Bria.ai

How to remove image backgrounds in Python (2027 guide)

Updated 2026-12-01

TL;DR

  • Direct answer: install rembg, open the file with Pillow, call remove() and save a PNG. For a hosted route, call the Bria API from the bria-client SDK.

  • Install: pip install "rembg[cpu]" pillow. Use rembg[gpu] if you have a supported GPU.

  • Edges: rembg has 4 edge modes. Start with decontaminate=True and reach for alpha matting only on hair or fur.

  • Batch: create one session with new_session() and reuse it for every file, or run rembg p on a folder.

  • API: the Bria API costs $0.018 per image for RMBG 3.0 (checked 2026-11-29) and runs as an async job you poll.

  • Pick by workload: local rembg is enough for scripts and prototypes. An API pays off when you need no GPU, a commercial path and predictable throughput.

Bria wrote this guide. Any benchmark figure in it is Bria's own benchmark, built from blind votes by professional and casual users plus a VLM side by side. The code below is copied from the rembg and Bria documentation and was not run for this article, so test it on your own images first.

How do I install rembg and cut out one image?

Install `rembg[cpu]` with Pillow, open the image, call `remove()` and save the result as PNG. The rembg README lists Python 3.11 up to, but not including, 3.14, and offers rembg[cpu], rembg[gpu] and rembg[rocm] installs (checked 2026-12-01).

pip install "rembg[cpu]" pillow
from rembg import remove
from PIL import Image

img = Image.open("input.jpg")
cutout = remove(img)
cutout.save("output.png")
  • The first call downloads the model to ~/.rembg/models/, so it runs slower once.

  • The default model is bria-rmbg, which is RMBG 2.0, about 1.02 GB.

  • remove() takes a PIL image, bytes or a NumPy array, and returns the same kind of object.

  • Save as PNG. JPEG has no alpha channel, so Pillow raises an error when you save an RGBA cutout as JPEG.

Flow diagram of two Python routes to a transparent PNG: local rembg and the Bria API.

How do I choose a model in rembg?

Pass a model name to `new_session()` and hand the session to `remove()`. The README lists models such as u2net, u2netp, silueta, isnet-general-use and the birefnet-* family, plus bria-rmbg as the default.

from rembg import remove, new_session
from PIL import Image

session = new_session("birefnet-general")
cutout = remove(Image.open("input.jpg"), session=session)
cutout.save("output.png")
  • BiRefNet powers the birefnet-* models. Its Hugging Face card lists an MIT license.

  • U2-Net powers u2net. The README says -m u2net gives a smaller, faster model with blockier edges.

  • For portraits, the README suggests birefnet-portrait with -dc as a good start.

  • Model weights carry their own licenses, independent of rembg's MIT license. Read the license of the model you ship.

What do the rembg edge options do?

Start with `decontaminate=True`, then try alpha matting only if soft edges still look wrong. The README's edge-mode table covers 4 modes, and the keyword arguments below come from rembg's remove() signature and USAGE.md.

  • Edge mode: Naive (default); How to set it in Python: remove(img); Notes from the README: Fast, no extra step

  • Edge mode: Decontaminate; How to set it in Python: remove(img, decontaminate=True); Notes from the README: Removes color fringing, alpha unchanged

  • Edge mode: Alpha matting; How to set it in Python: remove(img, alpha_matting=True); Notes from the README: Slow, helps most with older models on hair

  • Edge mode: ViTMatte; How to set it in Python: remove(img, vitmatte=True); Notes from the README: Slow, extra download of about 110 MB

Source: rembg README and bg.py, checked 2026-12-01.

# Tuned alpha matting, thresholds from rembg USAGE.md
cutout = remove(
    img,
    alpha_matting=True,
    alpha_matting_foreground_threshold=270,
    alpha_matting_background_threshold=20,
    alpha_matting_erode_size=11,
)

mask = remove(img, only_mask=True)          # mask only
white = remove(img, bgcolor=(255, 255, 255, 255))  # solid background
  • Newer models such as bria-rmbg and the birefnet-* family rarely need alpha matting, per the README.

  • Older models such as u2net and silueta give blockier edges and gain the most from it.

  • For batches the README prefers decontamination over alpha matting.

  • post_process_mask=True post-processes the mask, and force_return_bytes=True always returns bytes.

Cheat sheet table of rembg remove() arguments with their defaults.

How do I remove backgrounds from a whole folder?

Create one session and reuse it, so the model loads once instead of once per image. The README shows this pattern for folders of files:

from pathlib import Path
from rembg import remove, new_session

session = new_session()

for file in Path("path/to/folder").glob("*.png"):
    output_path = file.parent / (file.stem + ".out.png")
    with open(file, "rb") as i, open(output_path, "wb") as o:
        o.write(remove(i.read(), session=session))
  • The same job runs from a shell with rembg p, which processes a folder. Install the CLI extra with pip install "rembg[cpu,cli]".

  • Passing bytes in returns bytes out, so you can write the result straight to disk or storage.

How do I call the Bria API from Python?

Install `bria-client`, set `BRIA_API_TOKEN`, then submit a job to `image/edit/remove_background` and poll it. The SDK needs Python 3.10 or newer and is MIT licensed (Python SDK docs, checked 2026-12-01).

pip install bria-client
from bria_client import BriaSyncClient
from bria_client.toolkit import Image

client = BriaSyncClient()  # reads BRIA_API_TOKEN

job = client.submit(
    endpoint="image/edit/remove_background",
    payload={
        "image": Image("input.jpg").as_bria_api_input,
        "model": "RMBG3",
    },
)
result = client.poll(job, interval=2, timeout=120)
print(result.result.image_url)
  • Image() accepts a URL, a local path, a PIL image or a NumPy array.

  • model takes RMBG2 (the default) or RMBG3. Sending prompt with RMBG 3.0 returns a 422.

  • preserve_alpha and webhook_url are optional request fields in the background removal reference.

  • Input is JPEG, PNG or WEBP, sent as a URL or base64. Other types return 415.

  • Do not put sync in the payload. client.run(...) sets it for you.

  • The API answers 200 with result.image_url for a synchronous call, or 202 with a request_id and status_url for an async job.

The Bria API request fields shown here are the ones the reference documents. This guide does not show edge-tuning options for the API.

How do I batch images through the Bria API?

Loop over files, submit and poll each one, download the result and pace requests under your plan's limit. Limits are 10 requests per minute on Free, 60 on Pay-as-you-go and 1000 on Enterprise, and going over returns 429 (rate limits and errors).

import time
import urllib.request
from pathlib import Path
from bria_client import BriaSyncClient
from bria_client.toolkit import Image

client = BriaSyncClient()

for file in Path("photos").glob("*.jpg"):
    job = client.submit(
        endpoint="image/edit/remove_background",
        payload={"image": Image(str(file)).as_bria_api_input, "model": "RMBG3"},
    )
    result = client.poll(job, interval=2, timeout=120)
    urllib.request.urlretrieve(result.result.image_url, file.with_suffix(".png"))
    time.sleep(2)  # pace requests, status polls also count toward the limit

On the Free tier (10 requests per minute), raise the time.sleep and the poll interval well above 2 seconds.

  • Status polls count toward the limit, so each image costs at least two requests. At 60 requests per minute, 600 images take about 20 minutes.

  • Status calls count toward the limit, so poll with backoff and honor Retry-After on a 429.

  • For big queues, use webhook_url so you do not poll at all.

When is local rembg enough, and when does an API pay off?

Use local rembg for scripts, prototypes and one-off folders. Use the API when the code ships to paying users or you have no GPU. The table sets out the trade-offs.

  • Question: Install; Local rembg: pip install "rembg[cpu]"; Bria API: pip install bria-client plus an API key

  • Question: Hardware; Local rembg: Your CPU or GPU; Bria API: None on your side

  • Question: Cost per image; Local rembg: No fee, you pay for hardware; Bria API: $0.018 for RMBG 3.0 (checked 2026-11-29)

  • Question: Commercial use; Local rembg: Default model needs a paid agreement; Bria API: Commercial path is the API

  • Question: Throughput; Local rembg: Bound by your machine; Bria API: Bound by the plan limit

Source: rembg README, Bria docs and bria.ai/pricing, checked 2026-12-01.

  • Arithmetic at $0.018 per image: 10,000 images cost $180.

  • The rembg README says the RMBG 2.0 license requires a paid agreement for commercial use.

  • Bria's benchmark placed RMBG 3.0 first among 6 models, with an average rank of 1.51 over 234 hard test images. The benchmark write-up explains the method.

  • The RMBG 3.0 weights are CC BY-NC 4.0, with commercial use needing a separate agreement. See bria.ai/rmbg for the commercial options.

What should I check before shipping?

Test on your own hardest images, confirm the model license and set a failure path for 429 and 415 responses.

  • Run 20 to 50 of your worst photos through each route and compare edges by eye.

  • Record which model each output came from.

  • Log request IDs so a failed job can be retried.

  • Re-check prices and limits on the linked pages, because both change.

Which route should you choose?

  • Choose local rembg if you run scripts, prototypes or one-off folders on hardware you control and want no per-image fee.

  • Choose the Bria API if the code ships to paying users or you have no GPU. It is hosted, at $0.018 per image for RMBG 3.0 (checked 2026-11-29).

  • Check the CC BY-NC 4.0 license first if you plan to run the open RMBG 3.0 weights commercially. See bria.ai/rmbg for the commercial options.

Related posts

FAQs

Run pip install "rembg[cpu]" pillow, open the file with Pillow, pass it to remove() and save the result as a PNG. The first call downloads the default model, about 1.02 GB, so it runs slower once. The README lists Python 3.11 up to, but not including, 3.14. Use rembg[gpu] if you have a supported GPU. Source for the Python range and install extras is the rembg README, checked 2026-12-01.

Transparency lives in the alpha channel, and JPEG does not have one. Save the cutout as PNG, for example cutout.save("output.png"). Pillow raises an error if you try to save an RGBA image as JPEG. If you need a flat background instead, pass bgcolor=(255, 255, 255, 255) to remove() for a solid white fill, then save in any format. The same fix applies to the Bria API, which also returns a PNG with a transparent background.

Create one session with new_session() and pass session=session to every remove() call, so the model loads once. Loop over a folder with pathlib, or run the rembg p command on a directory after installing the cli extra. For large batches the README prefers decontaminate over alpha matting, because matting is slow on every image. Reusing the session matters most for large folders, since model loading is the fixed cost per run.

Use it when soft edges such as hair or fur still look wrong after decontaminate=True. The README calls alpha matting slow and says newer models like bria-rmbg and the birefnet family rarely need it, while older models such as u2net gain the most. USAGE.md tunes it with foreground threshold 270, background threshold 20 and erode size 11. Alpha matting also exposes erode size, so tune it on a few hard images before running a whole batch.

Follow us on social media

discord
Social media logo
Social media card
Social media logo
Social media card
Social media logo