No API key · Runs locally · MIT License

Background removal,
removed_bg.py

A single-file Python CLI that strips backgrounds from any image — using deep learning or fast colour-key. No API key. No cloud. Everything runs on your machine.

Before
After

Pick the right tool for the job

AI for anything. Colour-key for fast, logo-style work. Both output a clean RGBA PNG.

Method 1 — AI (U2-Net)

Deep learning via rembg. Handles hair, fur, glass, and complex scenes. Downloads the model once (~170 MB) and runs fully offline after that.

Any image Hair & fur Semi-transparent GPU optional

Method 2 — Colour-key

Pure NumPy + Pillow. Euclidean distance in RGB space with a Gaussian-blurred alpha mask. Lightning fast for logos with solid backgrounds.

Logos Solid backgrounds Fully offline Zero extra deps
Method 1 — AI Method 2 — Colour-key
Best forAny image — photos, logos, complex scenesLogos with a solid, uniform background
QualityProfessional (hair, fur, glass)Good for flat-background images
SpeedSlower (model inference)⚡ Fast (pure NumPy)
OfflineAfter first model download✔ Fully offline
GPU acceleration✔ CUDA GPU supported (via --gpu)❌ CPU only (no model inference needed)
Extra depsrembg + onnxruntimePillow + numpy only

Up and running in minutes

Python 3.8+ required. Tested on 3.9 through 3.12.

01

Clone the repo

Single file — no package structure needed.

02

Install core deps

Pillow and numpy are always required.

03

Add AI deps (optional)

Only needed for --method ai. Choose CPU or GPU.

04

Run it

Model downloads once on first AI run, then cached forever.

bash
# 1. Clone
git clone https://github.com/Biraj2004/removed_bg
cd removed_bg

# 2. Core deps (always)
pip install Pillow numpy

# 3a. AI method — CPU
pip install rembg onnxruntime

# 3b. AI method — NVIDIA GPU
pip install rembg onnxruntime-gpu

# Or use requirements.txt
pip install -r requirements.txt

Batch process entire folders with remove_bg.bat

A safe, CMD-based automation runner built right into the repository. Double-click, drag & drop, or run from terminal.

Strict 1-Folder Scope

Operates strictly on the single working directory you provide. Subdirectories are never entered, ensuring your nested folders remain untouched.

Single directory No subfolder recursion Safe

Dual Safety Gates [Y/N]

Never runs blindly. Displays pre-flight dependency diagnostics, scans the folder, lists all detected images, and requires explicit Y/N confirmation before starting.

Interactive safety Dependency prompt Pre-flight preview

Preserves Names with Suffix

Outputs are saved alongside original photos as <filename>_bg-removed.png. Existing processed outputs are automatically skipped on re-runs.

_bg-removed suffix Duplicate protection PNG RGBA

100% Standalone & Portable

Works even if you only have remove_bg.bat. Automatically bootstraps Python via winget, downloads the engine from GitHub, and installs pip packages on demand.

Auto-bootstrap Winget Python GitHub fetch
CMD / Windows Batch Usage
:: 1. Run in current folder (processes all images inside)
remove_bg.bat

:: 2. Target a specific folder
remove_bg.bat "D:\ECommerce\NewProducts"

:: 3. Drag-and-Drop: Simply drag any folder and drop it onto remove_bg.bat

Three ways to pass input

Single file, glob pattern, or an entire directory — all handled.

single file
# AI method (defaults to bg-removed-photo.png)
python removed_bg.py photo.jpg

# Force GPU acceleration
python removed_bg.py photo.jpg --gpu

# Preserved name with custom suffix (e.g. photo_bg-removed.png)
python removed_bg.py photo.jpg --suffix _bg-removed

# Colour-key — auto-detect background color (looks at corners)
python removed_bg.py signature.png --method colorkey

# Explicit output path with custom model
python removed_bg.py photo.jpg out/clean.png --model u2net
remove_bg.bat — 1-click batch script
# Run directly inside target directory
remove_bg.bat

# Or specify target folder path:
remove_bg.bat "C:\Users\biraj\Pictures\Project"

# Features:
# 1. Environment & dependency pre-flight check
# 2. Interactive [Y/N] safety gate before starting
# 3. Only processes the active folder (subfolders skipped)
# 4. Saves as <name>_bg-removed.png with duplicate protection
glob pattern — always quote it
# Quote the pattern so the shell doesn't expand it
python removed_bg.py "images/*.png" --batch --out-dir ./nobg/

# Multiple patterns in one call
python removed_bg.py "icons/*.png" "banners/*.jpg" --batch --out-dir ./nobg/
directory (non-recursive)
# All supported images inside the folder
python removed_bg.py images/ --batch --method ai --out-dir ./output/

# Supported: .png .jpg .jpeg .webp .bmp .tiff
# Subdirectories are skipped
batch colour-key
# Colour-key on a folder, white background, soft edges
python removed_bg.py assets/ --batch \
  --method colorkey \
  --bg-color 255,255,255 \
  --tolerance 35 \
  --feather 3 \
  --out-dir ./nobg/

All flags at a glance

output
auto
Output PNG path. Defaults to bg-removed-<stem>.png in the same folder. Not used with --batch.
--method
ai
ai — deep learning. colorkey — fast solid-colour removal.
--model
isnet-general-use
AI model to use (ai method only). Examples: isnet-general-use (high accuracy), u2net (standard), u2netp (lightweight), sam.
--gpu
off
Force NVIDIA GPU execution (CUDAExecutionProvider). Errors out if CUDA is unavailable.
--bg-color R,G,B
auto
Background colour to remove (colorkey only). If auto, automatically samples the 4 corner pixels of the image. Example: 255,255,255 for white.
--tolerance N
30
RGB Euclidean distance threshold. Raise to 50–80 for JPEG artefacts. Colour-key only.
--feather N
3
Gaussian blur radius on the alpha mask (0–10) for smooth edges. Colour-key only.
--batch
off
Enable batch mode. Required for multiple files, glob patterns, or a directory.
--prefix PREFIX
bg-removed-
Prefix added to output filename. Automatically cleared when --suffix is specified.
--suffix SUFFIX
—
Suffix appended to output filename before extension (e.g. _bg-removed as used by remove_bg.bat).
--out-dir DIR
—
Output directory for batch mode. Created automatically if it doesn't exist.
--dry-run
off
Preview resolved input files and target output paths without performing inference or saving files.
--check-env
—
Run pre-flight diagnostics on Python environment, required pip packages, and local model caches.
--quiet
off
Suppress all log output. Errors still appear on stderr. Useful in shell pipelines.
--version
—
Print the script version and exit.

Under the hood

AI — U2-Net via rembg

1

Open image and convert to RGBA.

2

Feed to U2-Net ONNX model. It predicts per-pixel foreground probability.

3

Apply alpha matte — handles hair, fur, semi-transparent edges.

4

Save RGBA PNG. Model cached at ~/.u2net/ after first run.

Colour-key algorithm

1

Convert to RGBA float32. Resolve background color (auto-detects from corners if set to auto).

2

Per-pixel Euclidean distance from --bg-color in RGB space: dist = √((R−Br)²+(G−Bg)²+(B−Bb)²)

3

Build alpha mask: dist < tol → 0.0 · linear ramp in feather zone · dist ≥ 2×tol → 1.0

4

Gaussian blur (radius = --feather) for sub-pixel anti-aliasing. Write RGBA PNG.

── Quality report printed after every run ──

stdout
── Quality report ───────────────────────────────────────────────
   Size          :   1790 × 1790 px
   Transparent   :   1,717,673  (53.6%)
   Opaque        :   1,291,422  (40.3%)
   Semi-trans    :     195,005  ( 6.1%)  ← edge matting
   Corner alphas : [0, 0, 0, 0]  ← should all be ≈ 0 if BG removed
─────────────────────────────────────────────────────────────────

Semi-transparent pixels = edge matting. Healthy range: 3–10%. Too low = jagged edges. Too high = BG colour bleeding into subject.

What's inside

No cloud APIs. No web services. Pure local processing.

Python 3.8+

Runtime. Tested on 3.9, 3.10, 3.11, 3.12.

Pillow

Image I/O, Gaussian blur, RGBA operations.

NumPy

Vectorised per-pixel distance and mask computation.

rembg

U2-Net model wrapper for the AI method.

onnxruntime

ONNX inference engine — CPU and CUDA GPU.

Good to know

Colour-key needs a uniform background. Don't use it on photos, gradients, or JPEG-heavy edges. Use --method ai instead.

AI method requires the U2-Net model. Downloaded automatically to ~/.u2net/ on first run. In restricted networks, pre-download it manually.

Directory scanning is non-recursive. Only files directly inside the given folder are processed. Subdirectories are skipped.

Very fine detail may need touch-up. Individual hairs, wispy smoke, or transparent glass may not be perfectly matted even with AI — a quick pass in a graphics editor can fix it.