Instructions to use moonbox-dev/BEN2-TensorRT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- TensorRT
How to use moonbox-dev/BEN2-TensorRT with TensorRT:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- BEN2
How to use moonbox-dev/BEN2-TensorRT with BEN2:
import requests from PIL import Image from ben2 import AutoModel url = "https://huggingface.co/datasets/mishig/sample_images/resolve/main/teapot.jpg" image = Image.open(requests.get(url, stream=True).raw) model = AutoModel.from_pretrained("moonbox-dev/BEN2-TensorRT") model.to("cuda").eval() foreground = model.inference(image) - Notebooks
- Google Colab
- Kaggle
File size: 1,677 Bytes
deb2b83 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | """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])
|