Files
BGfilter/bgfilter/cli.py
T
lhk229 7555321cfc Simplify to single-segmenter pipelines; add screen_color prior; drop rescue + recolor
Strategic pivot: the dropout-fill rescue, the anime-seg fill backend, the
BiRefNet+anime-seg intersection, and the recolor pass all existed to repair
source images whose hair was already green-contaminated or broken at generation
time. Fixing the source instead (clean pastel-background generation) makes the
matte high-contrast, so that whole compensation layer is unnecessary. Remove it.

- Two pipelines via segmentation.enabled:
    false -> chroma-only (Chroma + ViTMatte)
    true  -> single segmenter (default anime-seg, switchable birefnet) -> trimap
  then ViTMatte refines, pymatting estimates foreground, despill cleans spill.

- Generalise the green-hardcoded colour logic to a screen_color prior (hex, e.g.
  "#CFEFFF"; default null = green auto-detect, byte-identical). chroma keys off
  Lab/RGB distance to the colour; despill removes chroma along its Lab direction.
  Added --screen-color CLI flag.

- Removed dead code: fill_seg_dropouts + seg_fill*/intersection params,
  SegmentationSettings.fill_backend/fill_model_name/sharpen, unsharp_mask,
  recolor.py + RecolorSettings.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 15:33:58 +08:00

79 lines
3.7 KiB
Python

from __future__ import annotations
from pathlib import Path
import typer
from rich import print
from .config import load_settings, override_settings
from .pipeline import MattingPipeline, run_image
app = typer.Typer(help="Offline green screen character matting.")
@app.command()
def main(
input: Path | None = typer.Option(None, "--input", "-i", exists=True, file_okay=True, dir_okay=False),
output: Path | None = typer.Option(None, "--output", "-o", file_okay=True, dir_okay=False),
input_dir: Path | None = typer.Option(None, "--input-dir", exists=True, file_okay=False, dir_okay=True),
output_dir: Path | None = typer.Option(None, "--output-dir", file_okay=False, dir_okay=True),
debug_dir: Path | None = typer.Option(None, "--debug-dir", file_okay=False, dir_okay=True),
config: Path | None = typer.Option(None, "--config", exists=True, file_okay=True, dir_okay=False),
model_name: str | None = typer.Option(None, "--model-name"),
device: str | None = typer.Option(None, "--device"),
screen_color: str | None = typer.Option(None, "--screen-color", help="Background colour prior as #RRGGBB (default: auto-detect green screen)"),
matting_method: str | None = typer.Option(None, "--matting-method"),
fallback_to_chroma_alpha: bool | None = typer.Option(None, "--fallback-to-chroma-alpha/--no-fallback-to-chroma-alpha"),
sure_bg_threshold: float | None = typer.Option(None, "--sure-bg-threshold", min=0.0, max=1.0),
sure_fg_threshold: float | None = typer.Option(None, "--sure-fg-threshold", min=0.0, max=1.0),
unknown_radius_ratio: float | None = typer.Option(None, "--unknown-radius-ratio", min=0.0),
fg_safe_radius_ratio: float | None = typer.Option(None, "--fg-safe-radius-ratio", min=0.0),
despill: bool | None = typer.Option(None, "--despill/--no-despill"),
) -> None:
try:
settings = override_settings(
load_settings(config),
model_name=model_name,
device=device,
screen_color=screen_color,
matting_method=matting_method,
fallback_to_chroma_alpha=fallback_to_chroma_alpha,
sure_bg_threshold=sure_bg_threshold,
sure_fg_threshold=sure_fg_threshold,
unknown_radius_ratio=unknown_radius_ratio,
fg_safe_radius_ratio=fg_safe_radius_ratio,
despill=despill,
)
if input_dir is not None:
if output_dir is None:
raise typer.BadParameter("--output-dir is required when --input-dir is used")
images = sorted(
p for p in input_dir.iterdir() if p.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp"}
)
if not images:
raise typer.BadParameter(f"No supported images found in {input_dir}")
pipeline = MattingPipeline(settings)
for image_path in images:
out_path = output_dir / f"{image_path.stem}_rgba.png"
dbg = None if debug_dir is None else debug_dir / image_path.stem
result = pipeline.run_image(image_path, out_path, dbg)
print(f"[green]wrote[/green] {result['output']}")
return
if input is None or output is None:
raise typer.BadParameter("Use either --input/--output or --input-dir/--output-dir")
result = run_image(input, output, debug_dir, settings)
print(f"[green]wrote[/green] {result['output']}")
except RuntimeError as exc:
print(f"[red]error:[/red] {exc}")
raise typer.Exit(code=1) from exc
except ValueError as exc:
print(f"[red]config error:[/red] {exc}")
raise typer.Exit(code=1) from exc
if __name__ == "__main__":
app()