lhk229 62f175948e Auto-detect the background colour (default); drop the green heuristic
Replace the hardcoded green-screen auto-detection with a general flat-colour
detector. When screen_color is null the background colour is now detected from the
image border (dominant colour of the border strip) and used directly as the chroma
model, with a failure gate that raises when the border is not one clean flat colour
(gradient / texture / subject filling the frame).

- chroma: add detect_background_color + _background_border_cluster; the null case of
  estimate_background_model samples the detected cluster directly (no seed search);
  compute_bg_confidence is now always perceptual (Lab/RGB distance). Removed the green
  heuristic (initial_green_candidates), the green multiplicative gating, the now-unused
  _smoothstep, and five green-only ChromaSettings fields.
- pipeline: reuse the detected colour for de-spill in the auto case.
- settings / default.yaml: add detect_* tuning fields; refresh screen_color docs.
- README: document auto-detection + the failure gate, trimap modes, birefnet config.

A supplied --screen-color hex still uses the seed-search refinement. Validated:
detects green / pastel / text samples correctly, raises on gradient / two-colour, CLI
exits 1 on failure, green and pastel mattes unchanged in quality.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 20:34:31 +08:00
2026-07-01 15:46:21 +08:00

BgFilter

Offline character matting for AI-generated images on a flat-colour background. The background colour is auto-detected from the image border (green, pastel, any flat colour); pass --screen-color to set it explicitly.

RGB input
  -> chroma bg-confidence (keyed to the auto-detected or given colour)
  -> [optional] semantic segmentation mask
  -> trimap -> ViTMatte -> alpha cleanup
  -> pymatting foreground -> despill -> RGBA PNG -> QA previews

Pipelines

Two pipelines, selected by segmentation.enabled in the config:

  • Chroma-only (enabled: false) — Chroma + ViTMatte, no segmentation model. Lightest / fastest; leans entirely on the colour key for topology.
  • Single segmenter (enabled: true, default) — one segmentation model drives the trimap topology (holes, hair), ViTMatte then refines the soft edges. Backend is switchable: anime-seg (default, ONNX, for anime characters) or birefnet (general salient objects — text, logos, photos; needs trust_remote_code). Use --config configs\birefnet.yaml for the BiRefNet backend.

Both share pymatting foreground estimation and a colour de-spill. There is no green-contamination rescue / recolour layer — with clean source images it is unnecessary, so it was removed.

The segmentation trimap defaults to directional mode (chroma + seg + a hue-direction split: it keeps a background-coloured garment such as a white shirt while dropping a background-hued residual such as blue trapped between hair strands). Switch with --trimap-mode seg (topology only, no hue split) or directional-hard-bg (aggressive — hard-removes background-hued pixels; can eat cool/shadowed white cloth).

Background colour

By default (screen_color: null) the background colour is auto-detected from the image border: the dominant flat colour of the border strip becomes the key colour. If the border is not one clean flat colour — a gradient, texture, or a subject filling the frame — detection fails with an error; pass --screen-color explicitly in that case.

To set it yourself, give a hex prior:

... --screen-color "#CFEFFF"

or screen_color: "#CFEFFF" in the config. Either way the chroma key scores pixels by perceptual (Lab/RGB) distance to the colour, and de-spill removes chroma along that colour's direction. (A supplied hex is refined against nearby border pixels; an auto-detected colour is used directly.)

Environment

Use the conda environment lightML.

conda activate lightML
pip install -r requirements.txt

If the shell is not activated, call the environment Python directly:

D:\MiniConda\envs\lightML\python.exe -m bgfilter.cli --help

Single Image

D:\MiniConda\envs\lightML\python.exe -m bgfilter.cli `
  --input Samples\TestImage.png `
  --output Outputs\TestImage_rgba.png `
  --debug-dir Outputs\TestImage_debug `
  --config configs\default.yaml `
  --device cuda

No --screen-color is needed — the background colour is auto-detected. Add --screen-color "#CFEFFF" only to override it. The CLI reads configs/default.yaml when --config is provided; command-line options override config values, so tuning usually happens in YAML while runtime choices (--device, --screen-color, --trimap-mode) stay on the command line.

Batch

D:\MiniConda\envs\lightML\python.exe -m bgfilter.cli `
  --input-dir Samples `
  --output-dir Outputs `
  --debug-dir Outputs\debug `
  --config configs\default.yaml `
  --device cuda

Chroma-alpha debug mode

--matting-method chroma skips ViTMatte and uses chroma confidence directly as the alpha seed. Useful for fast inspection of chroma confidence, trimap, and despill. (Distinct from the chroma-only pipeline above, which still runs ViTMatte.)

D:\MiniConda\envs\lightML\python.exe -m bgfilter.cli `
  --input-dir Samples `
  --output-dir Outputs\chroma `
  --debug-dir Outputs\chroma_debug `
  --config configs\default.yaml `
  --matting-method chroma `
  --device cpu

Outputs

For each processed image, the CLI writes an RGBA PNG and optional debug files:

bg_confidence.png
trimap.png
seg_mask.png          # segmentation pipeline only
alpha.png
foreground_rgb.png    # despilled foreground colour
color_mask.png        # per-pixel despill weight
preview_black.png
preview_white.png
preview_gray.png
preview_red.png
preview_blue.png
qa_grid.png
metadata.json

Quality Check

The quality checker measures alpha validity and edge spill on semi-transparent edge pixels.

D:\MiniConda\envs\lightML\python.exe -m bgfilter.quality_cli `
  Outputs\TestImage_rgba.png `
  --max-edge-green-excess-p95 0.30

Run the bundled sample smoke check:

D:\MiniConda\envs\lightML\python.exe scripts\smoke_samples.py `
  --samples-dir Samples `
  --output-dir Outputs\smoke_samples `
  --config configs\default.yaml `
  --device cpu `
  --fallback-to-chroma-alpha `
  --max-edge-green-excess-p95 0.30

Notes

  • Samples/ and Outputs/ are ignored by Git.
  • ViTMatte and segmentation weights load from Hugging Face on first use. Behind a firewall set HF_ENDPOINT=https://hf-mirror.com (and bypass a flaky local proxy). anime-seg (skytnt/anime-seg) is a plain ONNX download; birefnet (ZhengPeng7/BiRefNet) ships custom modelling code so it needs trust_remote_code=True plus timm / einops / kornia.
  • Foreground colour estimation uses pymatting's estimate_foreground_ml to propagate clean foreground colour into semi-transparent edges before de-spill. Set foreground.method: unmix to fall back to the legacy heuristic.
  • docs/green_screen_matting_workflow.md is the original phase-1 green-screen spec; this README reflects the current, generalised architecture.
S
Description
No description provided
Readme 1 MiB
Languages
Python 100%