abu-hanif-prism/bg_removal

Python

0

1 commits

updated Sep 26, 2026

See the code

README

Portrait Lab — CPU Background Removal Benchmark

A CPU-only, self-hosted website for comparing seven background-removal models on human photos. The browser works on desktop, tablet, and phone. A Windows, macOS, or Linux computer runs the models; no GPU is required.

Features

  • Compare seven model integrations on the same photos, with all inference on the host CPU.
  • Upload multiple photos, adjust working resolution, and configure warm-up and measured passes.
  • Compare transparent cutouts and alpha masks on different backgrounds; inspect edges at original pixel size.
  • Measure processing time, model loading, RAM, CPU time, and output size.
  • Supply an optional reference mask for alpha MAE and IoU; record your own quality ratings and notes.
  • Save runs locally and export CSV, PNG, or a ZIP containing the complete results.
  • Open the same workspace from other devices on your private network.

Six models have passed real CPU inference checks. BRIA RMBG 2.0 needs authorized access to its gated weights. See validation results for tested platforms and limitations.

Get the project

git clone https://github.com/abu-hanif-prism/bg_removal.git
cd bg_removal

Alternatively, choose Code → Download ZIP on GitHub and extract it before launching.

You need 64-bit Python 3.11 and an internet connection for initial setup and model downloads, or Docker. Allow several GB of disk space. The larger models use substantially more RAM and CPU time than MediaPipe or MODNet. Python and model files are required only on the host computer, not on devices accessing its website.

This is a Python-backed application, so GitHub Pages cannot run it. Run it on your computer or a server using the instructions below.

Start on Windows

Install 64-bit Python 3.11, then double-click start-windows.bat. The first start installs dependencies in .venv; it does not need administrator access. The browser opens at http://localhost:7860.

Keep the terminal open while testing. Press Ctrl+C to stop the server. Subsequent launches reuse installed dependencies and cached model weights.

If the Python launcher is unavailable, run python setup.py, then .venv\Scripts\python.exe start.py from this folder. Setup requires Python 3.11 specifically.

Start on macOS or Linux

Install Python 3.11 and run bash start.sh. On Debian/Ubuntu you may need python3.11-venv, libgl1, libglib2.0-0, and libgomp1. Native support targets Windows x86-64, Linux x86-64, and macOS with compatible Python 3.11 wheels. Linux ARM64 is not supported by this pinned MediaPipe package.

Docker

With Docker installed, run:

docker compose up --build

Open http://localhost:7860. Stop with docker compose down; saved data remains in the local data directory. This CPU image uses Linux amd64; Apple Silicon Docker uses emulation and will be slower than a native macOS install. Docker configuration is supplied but has not been executed in the Windows validation environment.

Test from another device

Keep the host running, connect the other device to the same private network, and click Open on another device for the host's network URLs. Open one on your phone, tablet, or another computer. Allow Python/TCP 7860 through the host's private-network firewall if needed. Guest Wi-Fi/client isolation can block device-to-device access.

All clients share the host CPU, queue, and saved runs. Changing the browser device does not benchmark that device's CPU. To compare different CPUs, move this project to each computer and run its own server. For remote networks use your own VPN or authenticated hosting.

The app has no login and is intended for a trusted LAN. Do not expose port 7860 directly to the public internet. To limit it to one computer, run python start.py --host 127.0.0.1 using the virtual environment.

Move the project

Copy the source folder (or distribute dist/portrait-lab-portable.zip). Do not copy .venv: Python environments are machine-specific. Run the startup script on the new computer to install its dependencies. Optionally copy data/models to reuse cached weights and data/jobs to retain runs. The code contains no fixed drive letters. Model downloads require internet on first use; existing cached models can subsequently work offline. BRIA also requires account access for its initial download.

Allow several GB for dependencies and model weights. Large models can require several GB of RAM individually; 16 GB host RAM is a practical starting point for the complete suite, not a guaranteed minimum. Models run one at a time to avoid keeping all seven loaded. Start with MediaPipe, MODNet, and U²-Net on smaller computers.

Models

ModelImplementation / weightsNotes
BiRefNet PortraitOfficial HF checkpointPyTorch CPU, 1024×1024 internal input
MODNetOfficially linked ONNX exportPhotographic portrait model, ONNX CPU
U²-Net Humanrembg, u2net_human_segONNX CPU, 320×320 internal input
MediaPipe SelfieMediaPipeSquare selfie model, 256×256 internal input
BEN2Official code and public base weightsCPU, foreground refinement disabled
InSPyReNettransparent-background base modelCPU, static sizing, soft mask output
BRIA RMBG 2.0Official gated HF checkpointCPU, 1024×1024 internal input; access required

This app does not bundle or relicense upstream model weights. Each model's own license applies. Hugging Face models and BEN2 load upstream Python implementations; the official sources are linked above and downloaded to the model cache.

BRIA access

Accept/request access at https://huggingface.co/briaai/RMBG-2.0 with your Hugging Face account. Set an access token on the host, before starting the server:

# Windows PowerShell; use your own token, do not commit it
$env:HF_TOKEN = "your_hugging_face_token"
.\.venv\Scripts\python.exe start.py

On macOS/Linux use export HF_TOKEN=... before bash start.sh. Docker Compose forwards an existing HF_TOKEN environment variable. Tokens are never entered into or returned to the browser. BRIA commercial use requires its separate agreement; an internal company evaluation is not automatically covered by noncommercial terms.

If a Google Drive download fails, retry later or download the model manually from the official links. MODNet's file must be saved as data/models/modnet.onnx. Detailed worker logs are linked in failed result cards. A failing model does not stop the remaining models.

Testing workflow

  1. Upload 1–12 photos (JPG/PNG/WebP, max 25 MB and 24 MP each).
  2. Select models, working image size, measured passes, and warm-up passes.
  3. Run. Results appear as each model finishes. First-use downloads can be large.
  4. View against checkerboard, white, black, or green. Inspect original/cutout with the reveal slider and 100% pixel view. Download RGBA PNGs or grayscale masks.
  5. Record a 1–5 human quality rating and notes (saved on change/blur).
  6. Export CSV measurements or ZIP with original images, cutouts, masks, CSV, and run JSON.

An optional reference mask is supported for a single image: use a same-size grayscale PNG, white foreground and black background, with soft grays where appropriate. Dimensions must match the EXIF-oriented photo. This enables alpha MAE and binary IoU at 0.5. A transparent cutout is not a grayscale reference mask.

What the numbers mean

  • Median/mean/min/max/stddev and samples: wall time for adapter preprocessing + inference + mask conversion at the working image size. No uploads, loading, warm-up, or final PNG writing. CPU-only is enforced even on GPU hosts.
  • Load seconds: imports, initialization, and any first-use downloads. This value is shared across images for that model; do not sum it once per photo.
  • Warm-up seconds: excluded from measured passes. Zero warm-ups deliberately includes cold first-inference behavior in the samples.
  • Postprocess ms: full-resolution mask resize, compositing, and saving two PNGs.
  • Peak RAM MB: process RSS sampled every 50 ms during one image, including loaded weights and warm-up. It is not whole-system RAM or exact allocator peak.
  • CPU seconds: user + system process time over all measured passes. It can exceed wall time because of parallel threads.
  • VRAM: not applicable for CPU runs, represented as blank/— rather than zero.
  • Alpha MAE / IoU: only available with a reference; no artificial quality score is inferred from the image.
  • Run total: wall time after leaving the queue, including loading and output work for all selected models.

The working image size preserves aspect ratio and caps the longest side; each architecture still uses its native internal input dimensions. Output PNGs retain the original oriented dimensions. Soft alpha is applied to the original colors uniformly; no foreground color decontamination. Input transparency is flattened on white so every model receives the same RGB photo. Model versions and checkpoint details are included in exported JSON/CSV. BiRefNet, BRIA, and BEN2 use pinned upstream revisions. Other downloads are managed by their pinned adapter packages or official links; archive the model cache with the run for reproducibility.

CPU thread use is capped at up to eight threads where supported; some third-party runtimes may manage their own pools. Keep hardware, working size, warm-ups, and background load consistent when comparing runs. For visual quality include curly/flyaway hair, full bodies, groups, low contrast, busy backgrounds, and held objects.

Development checks

After initial setup, activate the virtual environment:

# Windows PowerShell
.\.venv\Scripts\Activate.ps1
# macOS / Linux
source .venv/bin/activate

Then run:

python -m pip install pytest httpx playwright
python -m pytest tests -q

Browser tests in tools/browser_check.py use installed Edge on Windows, or Chromium installed with python -m playwright install chromium. Start the server in another terminal, then run python tools/browser_check.py. These browser checks create a small test run in the local workspace. They do not represent a portrait-quality benchmark.

The test suite checks validation, export safety, reference metrics, persisted runs, and a real CPU MediaPipe inference. It does not download every large checkpoint. See VALIDATION.md for checks actually performed in this workspace.

Configuration

SettingDefaultHow to change it
Server port7860python start.py --port 7861, or the PORT environment variable
Network binding0.0.0.0 (LAN accessible)python start.py --host 127.0.0.1 for this computer only
Data folderdata/ beside the applicationSet BGLAB_DATA to an absolute directory path
BRIA authenticationNoneSet HF_TOKEN in the host environment before launching
Automatic browser openingEnabledAdd --no-browser to python start.py

Run these commands with the virtual environment active, or use its Python executable directly. In Docker, update the published port in compose.yaml if you want a different external port.

Troubleshooting

ProblemWhat to do
Python is missing or setup rejects the versionInstall 64-bit Python 3.11. On Windows, py -3.11 --version should succeed.
A dependency installation was interruptedRun python setup.py again with Python 3.11. The launcher retries setup when the completion marker is absent.
First run is taking a long timeModel weights download on first use. Loading and downloading are excluded from measured inference time. Use MediaPipe first to check the app quickly.
BRIA reports an access errorRequest/accept model access on Hugging Face and configure HF_TOKEN on the host; restart the server.
Another device cannot connectUse the host's private IP, keep both devices on the same network, and allow the port through the host's private-network firewall. Guest Wi-Fi can isolate devices.
Port 7860 is already in useStop the existing server or launch with --port 7861.
A model fails or runs out of RAMOpen its worker log from the error card. Try a smaller working image and fewer uploaded photos; close other memory-heavy applications. Native internal model sizes remain fixed.
Download failsCheck internet connectivity and the linked model provider, then retry. Completed weights remain cached.
Timings differ between devicesEach server uses its own CPU. Keep resolution, model versions, warm-ups, and background workload consistent. Accessing one host from two browsers still measures the same host.

Project structure

app.py                  Web API, uploads, job queue, history, and exports
adapters.py             Integrations for the seven models
worker.py               Isolated CPU inference and benchmark measurements
catalog.py              Model names, descriptions, and source links
static/                 Responsive browser interface
setup.py                Project-local dependency installer
start.py                Server entry point
start-windows.bat        Windows launcher
start.sh                macOS/Linux launcher
Dockerfile              CPU-only container image
compose.yaml            Container launch and persistent data configuration
tests/                  Automated API, metrics, and process tests
tools/                  Browser checks and portable ZIP builder
data/                   Local photos, results, and weights (not committed)
VALIDATION.md           Recorded checks and known limitations

To build a portable source archive, run python tools/package.py. It creates dist/portrait-lab-portable.zip without photos, weights, credentials, or the local Python environment. Git also excludes these local files. The archive requires setup on each new host; it is not a standalone executable.

abu-hanif-prism/bg_removal

Python

0

1 commits

updated Sep 26, 2026

See the code

README

Portrait Lab — CPU Background Removal Benchmark

A CPU-only, self-hosted website for comparing seven background-removal models on human photos. The browser works on desktop, tablet, and phone. A Windows, macOS, or Linux computer runs the models; no GPU is required.

Features

  • Compare seven model integrations on the same photos, with all inference on the host CPU.
  • Upload multiple photos, adjust working resolution, and configure warm-up and measured passes.
  • Compare transparent cutouts and alpha masks on different backgrounds; inspect edges at original pixel size.
  • Measure processing time, model loading, RAM, CPU time, and output size.
  • Supply an optional reference mask for alpha MAE and IoU; record your own quality ratings and notes.
  • Save runs locally and export CSV, PNG, or a ZIP containing the complete results.
  • Open the same workspace from other devices on your private network.

Six models have passed real CPU inference checks. BRIA RMBG 2.0 needs authorized access to its gated weights. See validation results for tested platforms and limitations.

Get the project

git clone https://github.com/abu-hanif-prism/bg_removal.git
cd bg_removal

Alternatively, choose Code → Download ZIP on GitHub and extract it before launching.

You need 64-bit Python 3.11 and an internet connection for initial setup and model downloads, or Docker. Allow several GB of disk space. The larger models use substantially more RAM and CPU time than MediaPipe or MODNet. Python and model files are required only on the host computer, not on devices accessing its website.

This is a Python-backed application, so GitHub Pages cannot run it. Run it on your computer or a server using the instructions below.

Start on Windows

Install 64-bit Python 3.11, then double-click start-windows.bat. The first start installs dependencies in .venv; it does not need administrator access. The browser opens at http://localhost:7860.

Keep the terminal open while testing. Press Ctrl+C to stop the server. Subsequent launches reuse installed dependencies and cached model weights.

If the Python launcher is unavailable, run python setup.py, then .venv\Scripts\python.exe start.py from this folder. Setup requires Python 3.11 specifically.

Start on macOS or Linux

Install Python 3.11 and run bash start.sh. On Debian/Ubuntu you may need python3.11-venv, libgl1, libglib2.0-0, and libgomp1. Native support targets Windows x86-64, Linux x86-64, and macOS with compatible Python 3.11 wheels. Linux ARM64 is not supported by this pinned MediaPipe package.

Docker

With Docker installed, run:

docker compose up --build

Open http://localhost:7860. Stop with docker compose down; saved data remains in the local data directory. This CPU image uses Linux amd64; Apple Silicon Docker uses emulation and will be slower than a native macOS install. Docker configuration is supplied but has not been executed in the Windows validation environment.

Test from another device

Keep the host running, connect the other device to the same private network, and click Open on another device for the host's network URLs. Open one on your phone, tablet, or another computer. Allow Python/TCP 7860 through the host's private-network firewall if needed. Guest Wi-Fi/client isolation can block device-to-device access.

All clients share the host CPU, queue, and saved runs. Changing the browser device does not benchmark that device's CPU. To compare different CPUs, move this project to each computer and run its own server. For remote networks use your own VPN or authenticated hosting.

The app has no login and is intended for a trusted LAN. Do not expose port 7860 directly to the public internet. To limit it to one computer, run python start.py --host 127.0.0.1 using the virtual environment.

Move the project

Copy the source folder (or distribute dist/portrait-lab-portable.zip). Do not copy .venv: Python environments are machine-specific. Run the startup script on the new computer to install its dependencies. Optionally copy data/models to reuse cached weights and data/jobs to retain runs. The code contains no fixed drive letters. Model downloads require internet on first use; existing cached models can subsequently work offline. BRIA also requires account access for its initial download.

Allow several GB for dependencies and model weights. Large models can require several GB of RAM individually; 16 GB host RAM is a practical starting point for the complete suite, not a guaranteed minimum. Models run one at a time to avoid keeping all seven loaded. Start with MediaPipe, MODNet, and U²-Net on smaller computers.

Models

ModelImplementation / weightsNotes
BiRefNet PortraitOfficial HF checkpointPyTorch CPU, 1024×1024 internal input
MODNetOfficially linked ONNX exportPhotographic portrait model, ONNX CPU
U²-Net Humanrembg, u2net_human_segONNX CPU, 320×320 internal input
MediaPipe SelfieMediaPipeSquare selfie model, 256×256 internal input
BEN2Official code and public base weightsCPU, foreground refinement disabled
InSPyReNettransparent-background base modelCPU, static sizing, soft mask output
BRIA RMBG 2.0Official gated HF checkpointCPU, 1024×1024 internal input; access required

This app does not bundle or relicense upstream model weights. Each model's own license applies. Hugging Face models and BEN2 load upstream Python implementations; the official sources are linked above and downloaded to the model cache.

BRIA access

Accept/request access at https://huggingface.co/briaai/RMBG-2.0 with your Hugging Face account. Set an access token on the host, before starting the server:

# Windows PowerShell; use your own token, do not commit it
$env:HF_TOKEN = "your_hugging_face_token"
.\.venv\Scripts\python.exe start.py

On macOS/Linux use export HF_TOKEN=... before bash start.sh. Docker Compose forwards an existing HF_TOKEN environment variable. Tokens are never entered into or returned to the browser. BRIA commercial use requires its separate agreement; an internal company evaluation is not automatically covered by noncommercial terms.

If a Google Drive download fails, retry later or download the model manually from the official links. MODNet's file must be saved as data/models/modnet.onnx. Detailed worker logs are linked in failed result cards. A failing model does not stop the remaining models.

Testing workflow

  1. Upload 1–12 photos (JPG/PNG/WebP, max 25 MB and 24 MP each).
  2. Select models, working image size, measured passes, and warm-up passes.
  3. Run. Results appear as each model finishes. First-use downloads can be large.
  4. View against checkerboard, white, black, or green. Inspect original/cutout with the reveal slider and 100% pixel view. Download RGBA PNGs or grayscale masks.
  5. Record a 1–5 human quality rating and notes (saved on change/blur).
  6. Export CSV measurements or ZIP with original images, cutouts, masks, CSV, and run JSON.

An optional reference mask is supported for a single image: use a same-size grayscale PNG, white foreground and black background, with soft grays where appropriate. Dimensions must match the EXIF-oriented photo. This enables alpha MAE and binary IoU at 0.5. A transparent cutout is not a grayscale reference mask.

What the numbers mean

  • Median/mean/min/max/stddev and samples: wall time for adapter preprocessing + inference + mask conversion at the working image size. No uploads, loading, warm-up, or final PNG writing. CPU-only is enforced even on GPU hosts.
  • Load seconds: imports, initialization, and any first-use downloads. This value is shared across images for that model; do not sum it once per photo.
  • Warm-up seconds: excluded from measured passes. Zero warm-ups deliberately includes cold first-inference behavior in the samples.
  • Postprocess ms: full-resolution mask resize, compositing, and saving two PNGs.
  • Peak RAM MB: process RSS sampled every 50 ms during one image, including loaded weights and warm-up. It is not whole-system RAM or exact allocator peak.
  • CPU seconds: user + system process time over all measured passes. It can exceed wall time because of parallel threads.
  • VRAM: not applicable for CPU runs, represented as blank/— rather than zero.
  • Alpha MAE / IoU: only available with a reference; no artificial quality score is inferred from the image.
  • Run total: wall time after leaving the queue, including loading and output work for all selected models.

The working image size preserves aspect ratio and caps the longest side; each architecture still uses its native internal input dimensions. Output PNGs retain the original oriented dimensions. Soft alpha is applied to the original colors uniformly; no foreground color decontamination. Input transparency is flattened on white so every model receives the same RGB photo. Model versions and checkpoint details are included in exported JSON/CSV. BiRefNet, BRIA, and BEN2 use pinned upstream revisions. Other downloads are managed by their pinned adapter packages or official links; archive the model cache with the run for reproducibility.

CPU thread use is capped at up to eight threads where supported; some third-party runtimes may manage their own pools. Keep hardware, working size, warm-ups, and background load consistent when comparing runs. For visual quality include curly/flyaway hair, full bodies, groups, low contrast, busy backgrounds, and held objects.

Development checks

After initial setup, activate the virtual environment:

# Windows PowerShell
.\.venv\Scripts\Activate.ps1
# macOS / Linux
source .venv/bin/activate

Then run:

python -m pip install pytest httpx playwright
python -m pytest tests -q

Browser tests in tools/browser_check.py use installed Edge on Windows, or Chromium installed with python -m playwright install chromium. Start the server in another terminal, then run python tools/browser_check.py. These browser checks create a small test run in the local workspace. They do not represent a portrait-quality benchmark.

The test suite checks validation, export safety, reference metrics, persisted runs, and a real CPU MediaPipe inference. It does not download every large checkpoint. See VALIDATION.md for checks actually performed in this workspace.

Configuration

SettingDefaultHow to change it
Server port7860python start.py --port 7861, or the PORT environment variable
Network binding0.0.0.0 (LAN accessible)python start.py --host 127.0.0.1 for this computer only
Data folderdata/ beside the applicationSet BGLAB_DATA to an absolute directory path
BRIA authenticationNoneSet HF_TOKEN in the host environment before launching
Automatic browser openingEnabledAdd --no-browser to python start.py

Run these commands with the virtual environment active, or use its Python executable directly. In Docker, update the published port in compose.yaml if you want a different external port.

Troubleshooting

ProblemWhat to do
Python is missing or setup rejects the versionInstall 64-bit Python 3.11. On Windows, py -3.11 --version should succeed.
A dependency installation was interruptedRun python setup.py again with Python 3.11. The launcher retries setup when the completion marker is absent.
First run is taking a long timeModel weights download on first use. Loading and downloading are excluded from measured inference time. Use MediaPipe first to check the app quickly.
BRIA reports an access errorRequest/accept model access on Hugging Face and configure HF_TOKEN on the host; restart the server.
Another device cannot connectUse the host's private IP, keep both devices on the same network, and allow the port through the host's private-network firewall. Guest Wi-Fi can isolate devices.
Port 7860 is already in useStop the existing server or launch with --port 7861.
A model fails or runs out of RAMOpen its worker log from the error card. Try a smaller working image and fewer uploaded photos; close other memory-heavy applications. Native internal model sizes remain fixed.
Download failsCheck internet connectivity and the linked model provider, then retry. Completed weights remain cached.
Timings differ between devicesEach server uses its own CPU. Keep resolution, model versions, warm-ups, and background workload consistent. Accessing one host from two browsers still measures the same host.

Project structure

app.py                  Web API, uploads, job queue, history, and exports
adapters.py             Integrations for the seven models
worker.py               Isolated CPU inference and benchmark measurements
catalog.py              Model names, descriptions, and source links
static/                 Responsive browser interface
setup.py                Project-local dependency installer
start.py                Server entry point
start-windows.bat        Windows launcher
start.sh                macOS/Linux launcher
Dockerfile              CPU-only container image
compose.yaml            Container launch and persistent data configuration
tests/                  Automated API, metrics, and process tests
tools/                  Browser checks and portable ZIP builder
data/                   Local photos, results, and weights (not committed)
VALIDATION.md           Recorded checks and known limitations

To build a portable source archive, run python tools/package.py. It creates dist/portrait-lab-portable.zip without photos, weights, credentials, or the local Python environment. Git also excludes these local files. The archive requires setup on each new host; it is not a standalone executable.