"""Background removal with a TensorRT engine (BiRefNet, BiRefNet_lite, ORMBG): a picture -> the picture with the matte as its alpha channel. python cutout_trt.py photo.jpg cutout.png The engine takes a 1024 x 1024 RGB picture [1, 3, 1024, 1024] (normalized as config.json says) and returns the matte [1, 1, 1024, 1024]. config.json: "norm" ("imagenet" or "none") and "minmax" (rescale the matte to 0-1, as ORMBG's inference does). """ from __future__ import annotations import json import sys from pathlib import Path import numpy as np from PIL import Image HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) from trt_runner import Engine # noqa: E402 MEAN_STD = {"imagenet": ([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), "none": ([0.0, 0.0, 0.0], [1.0, 1.0, 1.0])} def matte(engine, img, cfg): x = np.asarray(img.convert("RGB").resize((1024, 1024), Image.BILINEAR), np.float32) / 255 mean, std = MEAN_STD[cfg["norm"]] x = ((x - np.array(mean, np.float32)) / np.array(std, np.float32)).transpose(2, 0, 1)[None].copy() outs = engine({engine.inputs[0]: x}) y = next(o for o in outs.values() if o.ndim == 4 and o.shape[1] == 1 and o.shape[-1] == 1024) y = y[0, 0].astype(np.float32) if cfg.get("minmax"): y = (y - y.min()) / max(float(y.max() - y.min()), 1e-6) a = Image.fromarray((np.clip(y, 0, 1) * 255).astype(np.uint8)).resize(img.size, Image.BILINEAR) return a if __name__ == "__main__": cfg = json.loads((HERE / "config.json").read_text()) e = Engine(HERE / "model.engine") img = Image.open(sys.argv[1]).convert("RGB") img.putalpha(matte(e, img, cfg)) img.save(sys.argv[2])