Image Segmentation
ONNX
BiRefNet
background-removal
image-matting
onnxruntime
lucida
soft-alpha
transparency
rgba
Instructions to use PinkPixel/lucida-onnx with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- BiRefNet
How to use PinkPixel/lucida-onnx with BiRefNet:
# Option 1: use with transformers from transformers import AutoModelForImageSegmentation birefnet = AutoModelForImageSegmentation.from_pretrained("PinkPixel/lucida-onnx", trust_remote_code=True)# Option 2: use with BiRefNet # Install from https://github.com/ZhengPeng7/BiRefNet from models.birefnet import BiRefNet model = BiRefNet.from_pretrained("PinkPixel/lucida-onnx") - Notebooks
- Google Colab
- Kaggle
Download infer.py from PinkPixel/lucida-onnx: direct link, hf CLI and curl.
- Browser
- Download file 6.87 kB
-
https://huggingface.co/PinkPixel/lucida-onnx/resolve/main/infer.py
- Command line
-
hf download hf://PinkPixel/lucida-onnx/infer.py
-
curl -L -o infer.py https://huggingface.co/PinkPixel/lucida-onnx/resolve/main/infer.py
6.87 kB
| #!/usr/bin/env python3 | |
| """Lucida ONNX Background Removal and Image Matting Inference. | |
| Runs foreground segmentation and soft-alpha matting on images using | |
| the ONNX export of Lucida (BiRefNet HR backbone). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from pathlib import Path | |
| import sys | |
| import time | |
| try: | |
| import numpy as np | |
| import onnxruntime as ort | |
| from PIL import Image | |
| except ImportError as err: | |
| sys.exit( | |
| f"Missing required dependency: {err.name}\n" | |
| "Please install requirements: pip install -r requirements.txt" | |
| ) | |
| IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32) | |
| IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32) | |
| def get_providers(requested: str) -> list[str]: | |
| """Determine ONNX Runtime execution providers.""" | |
| available = ort.get_available_providers() | |
| if requested == "cuda": | |
| if "CUDAExecutionProvider" in available: | |
| return ["CUDAExecutionProvider", "CPUExecutionProvider"] | |
| print("Warning: CUDAExecutionProvider not available. Falling back to CPU.") | |
| return ["CPUExecutionProvider"] | |
| if requested == "cpu": | |
| return ["CPUExecutionProvider"] | |
| # auto | |
| if "CUDAExecutionProvider" in available: | |
| return ["CUDAExecutionProvider", "CPUExecutionProvider"] | |
| return ["CPUExecutionProvider"] | |
| def create_session(model_path: Path, provider: str) -> ort.InferenceSession: | |
| """Initialize an ONNX Runtime inference session.""" | |
| if not model_path.is_file(): | |
| raise FileNotFoundError(f"Model file not found: {model_path}") | |
| providers = get_providers(provider) | |
| session_options = ort.SessionOptions() | |
| session_options.graph_optimization_level = ( | |
| ort.GraphOptimizationLevel.ORT_ENABLE_ALL | |
| ) | |
| return ort.InferenceSession( | |
| str(model_path), sess_options=session_options, providers=providers | |
| ) | |
| def preprocess(image: Image.Image) -> tuple[np.ndarray, tuple[int, int]]: | |
| """Convert a PIL image to a normalized NCHW float32 tensor.""" | |
| orig_w, orig_h = image.size | |
| rgb_img = image.convert("RGB") | |
| resized = rgb_img.resize((1024, 1024), Image.Resampling.BILINEAR) | |
| arr = np.array(resized, dtype=np.float32) / 255.0 | |
| norm = (arr - IMAGENET_MEAN) / IMAGENET_STD | |
| tensor = np.transpose(norm, (2, 0, 1))[np.newaxis, ...] | |
| return tensor.astype(np.float32), (orig_w, orig_h) | |
| def postprocess( | |
| alpha_raw: np.ndarray, | |
| orig_size: tuple[int, int], | |
| original_image: Image.Image, | |
| mask_only: bool = False, | |
| ) -> Image.Image: | |
| """Transform raw model output into an alpha mask or transparent RGBA image.""" | |
| orig_w, orig_h = orig_size | |
| alpha_2d = np.squeeze(alpha_raw) | |
| alpha_clamped = np.clip(alpha_2d, 0.0, 1.0) | |
| alpha_uint8 = (alpha_clamped * 255.0).round().astype(np.uint8) | |
| alpha_mask = Image.fromarray(alpha_uint8, mode="L").resize( | |
| (orig_w, orig_h), Image.Resampling.BILINEAR | |
| ) | |
| if mask_only: | |
| return alpha_mask | |
| rgba = original_image.convert("RGBA") | |
| rgba.putalpha(alpha_mask) | |
| return rgba | |
| def process_file( | |
| session: ort.InferenceSession, | |
| input_path: Path, | |
| output_path: Path, | |
| mask_only: bool = False, | |
| ) -> None: | |
| """Process a single image file.""" | |
| start_time = time.perf_counter() | |
| image = Image.open(input_path) | |
| tensor, orig_size = preprocess(image) | |
| # Model input is named 'image', output is named 'alpha' | |
| input_name = session.get_inputs()[0].name | |
| outputs = session.run(None, {input_name: tensor}) | |
| alpha_output = outputs[0] | |
| result = postprocess(alpha_output, orig_size, image, mask_only=mask_only) | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| result.save(output_path) | |
| elapsed_ms = (time.perf_counter() - start_time) * 1000.0 | |
| print(f"Processed {input_path.name} -> {output_path.name} in {elapsed_ms:.1f} ms") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description="Run background removal with Lucida ONNX" | |
| ) | |
| parser.add_argument( | |
| "--image", | |
| "-i", | |
| type=Path, | |
| help="Path to an input image file", | |
| ) | |
| parser.add_argument( | |
| "--output", | |
| "-o", | |
| type=Path, | |
| help="Path to save the output PNG file", | |
| ) | |
| parser.add_argument( | |
| "--dir", | |
| "-d", | |
| type=Path, | |
| help="Directory of images to process in batch", | |
| ) | |
| parser.add_argument( | |
| "--output-dir", | |
| type=Path, | |
| default=Path("outputs"), | |
| help="Output directory for batch processing (default: outputs)", | |
| ) | |
| parser.add_argument( | |
| "--model", | |
| "-m", | |
| type=Path, | |
| default=Path(__file__).resolve().parent / "model.onnx", | |
| help="Path to the model.onnx file (default: model.onnx in script directory)", | |
| ) | |
| parser.add_argument( | |
| "--provider", | |
| "-p", | |
| choices=["auto", "cpu", "cuda"], | |
| default="auto", | |
| help="Execution provider (default: auto)", | |
| ) | |
| parser.add_argument( | |
| "--mask-only", | |
| action="store_true", | |
| help="Output only the grayscale alpha matte mask instead of transparent RGBA", | |
| ) | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| if not args.image and not args.dir: | |
| print("Error: Specify either --image or --dir. Use --help for usage details.") | |
| sys.exit(1) | |
| session = create_session(args.model, args.provider) | |
| active_providers = session.get_providers() | |
| print(f"Loaded model from {args.model.name} using {active_providers[0]}") | |
| if args.image: | |
| output_file = args.output | |
| if not output_file: | |
| stem = args.image.stem | |
| suffix = "_mask.png" if args.mask_only else "_cutout.png" | |
| output_file = args.image.with_name(f"{stem}{suffix}") | |
| process_file(session, args.image, output_file, mask_only=args.mask_only) | |
| if args.dir: | |
| if not args.dir.is_dir(): | |
| sys.exit(f"Error: Directory not found: {args.dir}") | |
| image_extensions = {".jpg", ".jpeg", ".png", ".webp", ".bmp"} | |
| files = [ | |
| f | |
| for f in args.dir.iterdir() | |
| if f.is_file() and f.suffix.lower() in image_extensions | |
| ] | |
| if not files: | |
| print(f"No matching images found in {args.dir}") | |
| return | |
| print(f"Processing {len(files)} image(s) from {args.dir}...") | |
| for file in sorted(files): | |
| stem = file.stem | |
| suffix = "_mask.png" if args.mask_only else "_cutout.png" | |
| out_file = args.output_dir / f"{stem}{suffix}" | |
| try: | |
| process_file(session, file, out_file, mask_only=args.mask_only) | |
| except Exception as ex: | |
| print(f"Failed processing {file.name}: {ex}", file=sys.stderr) | |
| if __name__ == "__main__": | |
| main() | |