Remove Background from Image in Python with rembg: Models, Batch, Masks and CLI (2026)

Automation Nov 25, 2026

Watch on YouTube

Product photos for an online shop, profile pictures, YouTube thumbnails, stickers, ID photos with a plain background: removing the background from an image is one of the most common image jobs, and most people still do it by hand in an editor or pay an online service per image. With Python you can do it locally, for free, for one photo or ten thousand. The library that makes this easy is rembg, an open-source tool that runs pre-trained segmentation models through ONNX Runtime and returns a transparent PNG. In 2026 rembg changed a lot: version 2.0.80 (August 2026) made the high-quality bria-rmbg model the default, moved models to ~/.rembg/models and added ViTMatte edge refinement, 2.0.79 added colour decontamination for soft edges, and 2.0.88, released on 24 November 2026, added a birefnet-dynamic session. In this tutorial we remove a background in one line, compare five models on speed and accuracy, process a whole folder, create masks, white product backgrounds, auto-cropped cutouts and new backgrounds, and use the command line tool. Everything was run on Python 3.14.10 with rembg 2.0.88, onnxruntime 1.32.0 and Pillow 13.0.0, and every output block below is the real output of the script above it.

No code needed? Try our free online Background Remover: it removes the background in your browser (your image is never uploaded) and gives you a transparent PNG.

Setup

rembg needs an ONNX Runtime backend. Install it with the cpu extra (or gpu if you have a CUDA card) and the cli extra if you want the rembg command. One important 2026 detail: onnxruntime has no wheels for Python 3.15 yet, so pip install rembg[cpu] fails on 3.15 with a resolver error. Create the virtual environment with Python 3.14 (3.11 to 3.14 all work).

uv venv -p 3.14 .venv            # or: python3.14 -m venv .venv
source .venv/bin/activate
pip install "rembg[cpu,cli]" pillow scikit-image
rembg --version                  # 2.0.88
rembg d u2netp isnet-general-use # optional: download models in advance

The first time you use a model, rembg downloads it to ~/.rembg/models/<model>/ (set REMBG_HOME to change the folder; the old U2NET_HOME variable still works and rembg m migrates the legacy ~/.u2net folder). Model sizes range from 4.4 MB for u2netp to about 1 GB for bria-rmbg, so download them once on a good connection. The sample photos come from scikit-image, which bundles a few free test images, so you can run every script without finding your own pictures.

Step 1: Remove a background in one line

remove() accepts a Pillow image, raw bytes or a NumPy array and returns the same type. With a Pillow image you get an RGBA image back: the subject keeps its colours and everything else gets alpha 0. Save it as PNG or WebP, never JPEG, because JPEG has no transparency.

from pathlib import Path
from time import perf_counter

import numpy as np
from PIL import Image
from skimage import data  # free sample photos bundled with scikit-image
from rembg import remove

Path("images").mkdir(exist_ok=True)
Path("output").mkdir(exist_ok=True)
samples = {"cat": data.chelsea(), "astronaut": data.astronaut(), "coffee": data.coffee()}
for name, pixels in samples.items():
    Image.fromarray(pixels).save(f"images/{name}.jpg", quality=95)

img = Image.open("images/cat.jpg")
start = perf_counter()
cutout = remove(img)  # default model in rembg 2.0.80+: bria-rmbg
seconds = perf_counter() - start

cutout.save("output/cat_no_bg.png")
alpha = np.asarray(cutout.getchannel("A"))
print("input :", img.size, img.mode)
print("output:", cutout.size, cutout.mode)
print(f"time  : {seconds:.2f} s (includes loading the model)")
print(f"subject pixels    : {(alpha > 127).mean():.1%}")
print(f"removed pixels    : {(alpha == 0).mean():.1%}")
print("subject box       :", cutout.getbbox())
input : (451, 300) RGB
output: (451, 300) RGBA
time  : 13.56 s (includes loading the model)
subject pixels    : 79.0%
removed pixels    : 19.8%
subject box       : (0, 0, 403, 300)

The default model is now bria-rmbg, and the 13.56 seconds include loading a 1 GB model; that is why you should never call remove() without a session inside a loop. About 79% of the pixels belong to the cat (alpha above 127) and 19.8% became fully transparent; the rest are soft edge pixels such as whiskers and fur, which is exactly what a good model should produce. getbbox() on an RGBA image returns the box around the non-transparent pixels, which we will use later to auto-crop.

Step 2: Compare the models

rembg ships many sessions. new_session(name) loads a model once and returns an object you pass to remove(). With only_mask=True you get just the black-and-white mask, which makes it easy to compare models. Here we test five general models on the astronaut photo and measure load time, run time and how much they agree with bria-rmbg using IoU (intersection over union of the subject pixels).

from time import perf_counter

import numpy as np
from PIL import Image
from rembg import new_session, remove

img = Image.open("images/astronaut.jpg")
models = ["u2netp", "u2net", "isnet-general-use", "birefnet-general-lite", "bria-rmbg"]
masks = {}
print(f"{'model':22} {'load s':>7} {'run s':>7} {'subject':>8}")
for name in models:
    t0 = perf_counter()
    session = new_session(name)
    t1 = perf_counter()
    mask = remove(img, session=session, only_mask=True)
    t2 = perf_counter()
    masks[name] = np.asarray(mask) > 127
    print(f"{name:22} {t1 - t0:7.2f} {t2 - t1:7.2f} {masks[name].mean():8.1%}")

ref = masks["bria-rmbg"]
print("\nagreement with bria-rmbg (IoU):")
for name in models[:-1]:
    iou = (masks[name] & ref).sum() / (masks[name] | ref).sum()
    print(f"  {name:22} {iou:.3f}")
model                   load s   run s  subject
u2netp                    0.05    0.11    54.8%
u2net                     0.75    0.15    54.4%
isnet-general-use         0.40    0.40    53.5%
birefnet-general-lite     1.31    6.21    53.0%
bria-rmbg                 3.64    7.71    53.4%

agreement with bria-rmbg (IoU):
  u2netp                 0.973
  u2net                  0.978
  isnet-general-use      0.997
  birefnet-general-lite  0.988

The results show the real trade-off. u2netp is tiny and runs in about a tenth of a second on CPU, but its edges are rough. isnet-general-use agrees with bria-rmbg on 99.7% of the subject pixels while being roughly twenty times faster, which makes it the best default for batch jobs on a normal machine. birefnet-general-lite and bria-rmbg give the cleanest edges on hair and fine details but take 6 to 8 seconds per image on CPU. Memory matters too: a script that only runs bria-rmbg peaked at about 9 GB of RAM on our Linux test box, so it is not a good choice for a small server.

ModelSizeBest forLicence note
u2netp4.4 MBvery fast previews, low-power machinesApache 2.0
u2net168 MBclassic general modelApache 2.0
u2net_human_seg168 MBpeople and portraitsApache 2.0
isnet-general-use171 MBbest speed/quality balance for batchesApache 2.0
isnet-anime168 MBanime and illustrationsApache 2.0
birefnet-general-lite214 MBhigh quality, fine edgesMIT
bria-rmbg (default)977 MBbest quality, hair and complex scenesRMBG-2.0 weights are non-commercial (CC BY-NC 4.0); check Bria's terms before commercial use

Step 3: Batch process a folder with one session

For real automation you usually have a folder of product photos or uploads. Create the session once, then loop over the files. Passing bytes in gives PNG bytes back, so you never need to decode or encode images yourself. pathlib keeps the paths clean.

from pathlib import Path
from time import perf_counter

from rembg import new_session, remove

session = new_session("isnet-general-use")  # load the model ONCE
out_dir = Path("output/batch")
out_dir.mkdir(parents=True, exist_ok=True)

for path in sorted(Path("images").glob("*.jpg")):
    start = perf_counter()
    png_bytes = remove(path.read_bytes(), session=session)  # bytes in -> PNG bytes out
    target = out_dir / f"{path.stem}.png"
    target.write_bytes(png_bytes)
    print(f"{path.name:14} -> {target}  {len(png_bytes) / 1024:6.1f} KB  {perf_counter() - start:.2f} s")
astronaut.jpg  -> output/batch/astronaut.png   288.3 KB  0.50 s
cat.jpg        -> output/batch/cat.png   235.4 KB  0.59 s
coffee.jpg     -> output/batch/coffee.png   208.6 KB  0.35 s

With the model already loaded, each image took well under a second on CPU. Compare that with the 13 seconds of step 1: reusing a session is the single biggest speed-up in rembg. For large jobs you can also run several worker processes, each with its own session, as long as you have enough RAM for one model per process.

Step 4: Masks, white backgrounds, clean edges and new backgrounds

A transparent PNG is only the start. Online shops often require a pure white background, designers want the mask to use in other tools, and thumbnails need the subject on a new background. All of this is a parameter away. We use isnet-general-use here to keep memory low.

from PIL import Image, ImageDraw
from rembg import new_session, remove

session = new_session("isnet-general-use")
img = Image.open("images/coffee.jpg")

# 1) black-and-white mask only
mask = remove(img, session=session, only_mask=True, post_process_mask=True)
mask.save("output/coffee_mask.png")
print("mask       :", mask.mode, mask.size, "values", mask.getextrema())

# 2) white background for a product photo (JPEG has no alpha)
white = remove(img, session=session, bgcolor=(255, 255, 255, 255))
white.convert("RGB").save("output/coffee_white.jpg", quality=92)
print("white bg   :", white.mode, "corner pixel", white.getpixel((5, 5)))

# 3) clean soft edges, then auto-crop to the subject
clean = remove(img, session=session, decontaminate=True)
box = clean.getbbox()
cropped = clean.crop(box)
cropped.save("output/coffee_cropped.png")
print("crop box   :", box, "->", cropped.size)

# 4) paste the cutout on a new gradient background
bg = Image.new("RGBA", img.size)
draw = ImageDraw.Draw(bg)
for y in range(img.height):
    draw.line([(0, y), (img.width, y)], fill=(30, 60 + y // 3, 160, 255))
bg.alpha_composite(clean)
bg.convert("RGB").save("output/coffee_new_bg.jpg", quality=92)
print("new bg     :", bg.size, "saved output/coffee_new_bg.jpg")
mask       : L (600, 400) values (0, 255)
white bg   : RGBA corner pixel (255, 255, 255, 255)
crop box   : (73, 14, 483, 400) -> (410, 386)
new bg     : (600, 400) saved output/coffee_new_bg.jpg
  • only_mask=True returns an L mode image; post_process_mask=True smooths it with morphological operations, which is why the values are only 0 and 255.
  • bgcolor=(255, 255, 255, 255) fills the background with an RGBA colour. Convert to RGB before saving as JPEG.
  • decontaminate=True (new in 2.0.79) estimates the real foreground colour on semi-transparent edge pixels, so you do not get a halo of the old background colour around hair or fur when you place the cutout on a new background.
  • clean.crop(clean.getbbox()) trims the empty transparent border, perfect for stickers and product images.
  • alpha_composite from Pillow places the cutout on any RGBA background. For more resizing, cropping and watermarking, see our Pillow tutorial: resize, crop and watermark images.

For the hardest edges, vitmatte=True (CLI -vm) refines the mask with a ViTMatte model; it is slower and downloads an extra model, so use it only when hair detail really matters. The older alpha_matting=True option still works as a lighter alternative.

Step 5: The rembg command line

You do not always need a script. The rembg command has i for one file, p for a folder, b for a byte stream, s for an HTTP server and d to download models. Here we call it from Python with subprocess so the run is recorded.

import subprocess
from pathlib import Path

commands = [
    ["rembg", "i", "-m", "u2netp", "images/cat.jpg", "output/cat_cli.png"],
    ["rembg", "p", "-m", "u2netp", "images", "output/cli_folder"],
]
for cmd in commands:
    result = subprocess.run(cmd, capture_output=True, text=True)
    print("$", " ".join(cmd), "-> exit", result.returncode)

for png in sorted(Path("output").rglob("*cli*/*.png")) + [Path("output/cat_cli.png")]:
    print(f"  {png}  {png.stat().st_size / 1024:.1f} KB")
$ rembg i -m u2netp images/cat.jpg output/cat_cli.png -> exit 0
$ rembg p -m u2netp images output/cli_folder -> exit 0
  output/cli_folder/astronaut.png  298.6 KB
  output/cli_folder/cat.png  214.8 KB
  output/cli_folder/coffee.png  211.6 KB
  output/cat_cli.png  214.8 KB

Useful flags: -m chooses the model, -om outputs only the mask, -bgc 255 255 255 255 sets a background colour, -dc turns on decontamination, and rembg p -w input/ output/ watches the input folder and processes every new image as it arrives, which is a complete background-removal pipeline in one command. rembg s --port 7000 starts a small HTTP API if you want to call it from another app.

Common problems and fixes

  • No matching distribution for onnxruntime: you are on Python 3.15 (or a free-threaded build without wheels). Use Python 3.14.
  • The process is killed or very slow: bria-rmbg needs several GB of RAM and seconds per image on CPU. Switch to isnet-general-use or u2netp, or install rembg[gpu] on a CUDA machine.
  • Every image is slow: you are calling remove() without a session, so the model reloads each time. Create new_session() once.
  • Black background after saving: you saved as JPEG. Use PNG or WebP, or set bgcolor.
  • Coloured halo around the subject: add decontaminate=True or try birefnet-general-lite.
  • Rotated phone photos: rembg already applies the EXIF orientation, so the cutout matches what you see.

Where to use it next

rembg fits naturally into other automation jobs on this site. Clean up scanned documents before running OCR in Python to extract text from images, or cut out a presenter or product and place it on new backgrounds in a video with MoviePy 2. Together with Pillow, these give you a complete, free image pipeline in Python.

Conclusion

Removing an image background in Python takes one function call: remove(img). For real projects, choose the model on purpose (isnet-general-use for fast batches, birefnet-general-lite or bria-rmbg for the best edges, and check the licence for commercial work), create one session and reuse it, and use the options for masks, white backgrounds, decontaminated edges and auto-cropping. Remember to use Python 3.14 until onnxruntime publishes Python 3.15 wheels.

FAQ

Is rembg free for commercial use? rembg itself is MIT licensed, and the U2-Net, ISNet and BiRefNet models are under permissive licences. The default bria-rmbg weights are non-commercial, so pick another model or get a licence from Bria for commercial products.

Does rembg need a GPU? No. All examples here ran on CPU. A GPU with rembg[gpu] makes the large models much faster.

Which model should I use? Start with isnet-general-use; it matched bria-rmbg on 99.7% of pixels in our test and is about twenty times faster on CPU.

Can rembg process a whole folder automatically? Yes, with a loop and one session in Python, or with rembg p input output, and add -w to keep watching the folder for new files.

Tested versions: Python 3.14.10, rembg 2.0.88, onnxruntime 1.32.0, Pillow 13.0.0, NumPy 2.5.5, scikit-image 0.26.0, pymatting 1.1.16 on Linux x86_64 (CPU only).

Share:
Last updated: November 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices