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.
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.
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.
| Method 1 — AI | Method 2 — Colour-key | |
|---|---|---|
| Best for | Any image — photos, logos, complex scenes | Logos with a solid, uniform background |
| Quality | Professional (hair, fur, glass) | Good for flat-background images |
| Speed | Slower (model inference) | ⚡ Fast (pure NumPy) |
| Offline | After first model download | ✔ Fully offline |
| GPU acceleration | ✔ CUDA GPU supported (via --gpu) | ❌ CPU only (no model inference needed) |
| Extra deps | rembg + onnxruntime | Pillow + numpy only |
Up and running in minutes
Python 3.8+ required. Tested on 3.9 through 3.12.
Clone the repo
Single file — no package structure needed.
Install core deps
Pillow and numpy are always required.
Add AI deps (optional)
Only needed for --method ai. Choose CPU or GPU.
Run it
Model downloads once on first AI run, then cached forever.
# 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.
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.
Preserves Names with Suffix
Outputs are saved alongside original photos as <filename>_bg-removed.png. Existing processed outputs are automatically skipped on re-runs.
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.
:: 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.
# 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
# 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
# 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/
# 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
# 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
Under the hood
AI — U2-Net via rembg
Open image and convert to RGBA.
Feed to U2-Net ONNX model. It predicts per-pixel foreground probability.
Apply alpha matte — handles hair, fur, semi-transparent edges.
Save RGBA PNG. Model cached at ~/.u2net/ after first run.
Colour-key algorithm
Convert to RGBA float32. Resolve background color (auto-detects from corners if set to auto).
Per-pixel Euclidean distance from --bg-color in RGB space: dist = √((R−Br)²+(G−Bg)²+(B−Bb)²)
Build alpha mask: dist < tol → 0.0 · linear ramp in feather zone · dist ≥ 2×tol → 1.0
Gaussian blur (radius = --feather) for sub-pixel anti-aliasing. Write RGBA PNG.
── Quality report printed after every run ──
── 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.