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
Model card and the original license
Browse filesFiles changed (8)
33 unmodified lines34353637383940414233 unmodified lines*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textfp16/model.engine filter=lfs diff=lfs merge=lfs -textBEN2_demo_pictures/grid_example1.png filter=lfs diff=lfs merge=lfs -textBEN2_demo_pictures/grid_example2.png filter=lfs diff=lfs merge=lfs -textBEN2_demo_pictures/grid_example3.png filter=lfs diff=lfs merge=lfs -textBEN2_demo_pictures/grid_example6.png filter=lfs diff=lfs merge=lfs -textBEN2_demo_pictures/grid_example7.png filter=lfs diff=lfs merge=lfs -textBEN2_demo_pictures/model_comparison.png filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226---base_model: PramaLLC/BEN2base_model_relation: quantizedlicense: mitpipeline_tag: image-segmentationlibrary_name: tensorrttags:- tensorrt- moonbox- ben2- background-removal- image-matting- image-segmentation---
# BEN2 Base TensorRT
TensorRT engines of [BEN2 Base](https://huggingface.co/PramaLLC/BEN2), made by Moonbox for NVIDIA RTX GPUs. Each precision is one folder holding theengine, `trt_runner.py` (a small numpy runner: TensorRT plus Polygraphy, no PyTorch) and a script that does the restof the pipeline. What the engine takes and returns is under *How to run*.
**Compatibility.** The engines are built *hardware compatible* (Ampere and newer: RTX 30, 40 and 50 series) and*version compatible* (any TensorRT 10.x from 10.13 on, through its lean runtime). That costs a little speed against anengine built for one GPU, but no rebuild is needed. Install the runtime with`pip install "tensorrt-cu12>=10.13,<11" "tensorrt-lean-cu12>=10.13,<11" polygraphy numpy`.
## Files
The last column is the benchmark (details under *How to run*).
| Precision | File | Size | sha256 | Benchmark ||---|---|---|---|---|| fp16 | [`fp16/config.json`](https://huggingface.co/moonbox-dev/BEN2-TensorRT/blob/main/fp16/config.json) | 0.0 kB | `5b1a91adebb1` | weakly typed: vs the fp16 ONNX IoU 0.9983, MAE 0.0003; DIS5K MAE 0.0244, S 0.937; 370 ms a picture (ONNX fp16 445 ms) || fp16 | [`fp16/cutout_trt.py`](https://huggingface.co/moonbox-dev/BEN2-TensorRT/blob/main/fp16/cutout_trt.py) | 1.7 kB | `5c0a5d2a60e5` | weakly typed: vs the fp16 ONNX IoU 0.9983, MAE 0.0003; DIS5K MAE 0.0244, S 0.937; 370 ms a picture (ONNX fp16 445 ms) || fp16 | [`fp16/model.engine`](https://huggingface.co/moonbox-dev/BEN2-TensorRT/blob/main/fp16/model.engine) | 490.2 MB | `2d4ac960f6f3` | weakly typed: vs the fp16 ONNX IoU 0.9983, MAE 0.0003; DIS5K MAE 0.0244, S 0.937; 370 ms a picture (ONNX fp16 445 ms) || fp16 | [`fp16/trt_runner.py`](https://huggingface.co/moonbox-dev/BEN2-TensorRT/blob/main/fp16/trt_runner.py) | 2.2 kB | `efa8ba97631b` | weakly typed: vs the fp16 ONNX IoU 0.9983, MAE 0.0003; DIS5K MAE 0.0244, S 0.937; 370 ms a picture (ONNX fp16 445 ms) |
## How to run
BEN2 (BEN2_Base, background erase network) as a TensorRT engine built from the official fp16 ONNX graph.
```pythonimport sysfrom PIL import Imagesys.path.insert(0, "fp16")import json, cutout_trtfrom trt_runner import Enginee = Engine("fp16/model.engine")cfg = json.load(open("fp16/config.json"))img = Image.open("photo.jpg").convert("RGB")img.putalpha(cutout_trt.matte(e, img, cfg)); img.save("cutout.png")```
Or `python fp16/cutout_trt.py photo.jpg cutout.png`. The engine takes the picture resized to 1024 x 1024, RGB in 0-1without normalization, as [1, 3, 1024, 1024]. It returns the matte [1, 1, 1024, 1024], rescaled to 0-1 as theoriginal's `onnx_run.py` does. `cutout_trt.py` resizes the matte back to the picture's size.
**Precisions.** `fp16/` is built *weakly typed*: TensorRT chooses each layer's precision itself, fp16 where it can,fp32 where it must. A strongly typed build that keeps every fp16 tensor as the ONNX graph has it overflows insideTensorRT's fused kernels: every output was NaN. No int8: TensorRT's int8 needs calibrated activations.
**Benchmark.**- **Data:** the [DIS5K](https://github.com/xuebinqin/DIS) test sets, 250 pictures (DIS-TE1..4 and DIS-VD, 50 each), on an RTX 3080 Laptop GPU.- **Reference:** the official fp16 ONNX graph, which is this model's own release (there is no fp32 one).- **Fidelity:** agreement with that reference's mattes: IoU of the masks at 0.5, mean absolute difference.- **Quality:** MAE and S-measure against the ground truth (PySODMetrics, masks shrunk to at most 2048 px).- **Pass mark:** MAE <= 0.005 and IoU >= 0.98 against the reference, as for this model's other builds.
| | vs the fp16 ONNX: IoU / MAE | DIS5K MAE / S-measure | ms a picture | peak GPU memory ||---|---|---|---|---|| ONNX fp16 (reference) | - | 0.0244 / 0.937 | 445 | 4515 MiB || TensorRT `fp16/` | 0.9983 / 0.0003 | 0.0244 / 0.937 | 370 | 2472 MiB |
The times are medians per picture, including the resizing to and from 1024 x 1024.
## How these were made
From [BEN2 Base](https://huggingface.co/PramaLLC/BEN2) at revision `e48a20765f`: each engine was built with TensorRT's builder from Moonbox's publishedONNX graph of the same model and precision. The network is *strongly typed*: every tensor keeps the precision theONNX graph gives it, so an fp16 engine computes what the fp16 ONNX build computes. Built on an RTX 3080 Laptop GPU,it was benchmarked against the original before upload, and the `sha256` column above is what the files must hash to.
## License
MIT. These files are a derivative of the original model and carry its license: it is copied in thisrepository, and it governs your use of these files. The original model card follows unchanged.
---
# Original model card
# BEN2: Background Erase Network
[](https://arxiv.org/abs/2501.06230)[](https://github.com/PramaLLC/BEN2/)[](https://backgrounderase.net)
## OverviewBEN2 (Background Erase Network) introduces a novel approach to foreground segmentation through its innovative Confidence Guided Matting (CGM) pipeline. The architecture employs a refiner network that targets and processes pixels where the base model exhibits lower confidence levels, resulting in more precise and reliable matting results. This model is built on BEN:[](https://paperswithcode.com/sota/dichotomous-image-segmentation-on-dis-vd?p=ben-using-confidence-guided-matting-for)
## BEN2 accessBEN2 was trained on the DIS5k and our 22K proprietary segmentation dataset. Our enhanced model delivers superior performance in hair matting, 4K processing, object segmentation, and edge refinement. Our Base model is open source. To try the full model through our free web demo or integrate BEN2 into your project with our API:- 🌐 [backgrounderase.com](https://backgrounderase.com)
## Contact us- For access to our commercial model email us at sales@backgrounderase.com- Our website: https://backgrounderase.com/- Follow us on X: https://x.com/PramaResearch/
## Installation
```pip install -e "git+https://github.com/PramaLLC/BEN2.git#egg=ben2"```
## Quick start code
```pythonfrom ben2 import BEN_Basefrom PIL import Imageimport torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
file = "./image.png" # input image
model = BEN_Base.from_pretrained("PramaLLC/BEN2")model.to(device).eval()
image = Image.open(file)foreground = model.inference(image, refine_foreground=False,) #Refine foreground is an extract postprocessing step that increases inference time but can improve matting edges. The default value is False.
foreground.save("./foreground.png")
```
## Batch image processing
```pythonfrom ben2 import BEN_Basefrom PIL import Imageimport torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = BEN_Base.from_pretrained("PramaLLC/BEN2")model.to(device).eval()
file1 = "./image1.png" # input image1file2 = "./image2.png" # input image2image1 = Image.open(file1)image2 = Image.open(file2)
foregrounds = model.inference([image1, image2]) # We recommend that the batch size not exceed 3 for consumer GPUs as there are minimal inference gains due to our custom batch processing for the MVANet decoding steps.foregrounds[0].save("./foreground1.png")foregrounds[1].save("./foreground2.png")
```
# BEN2 video segmentation[](https://www.youtube.com/watch?v=skEXiIHQcys)
## Video Segmentation
```bashsudo apt updatesudo apt install ffmpeg```
```pythonfrom ben2 import BEN_Basefrom PIL import Imageimport torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
video_path = "/path_to_your_video.mp4"# input video
model = BEN_Base.from_pretrained("PramaLLC/BEN2")model.to(device).eval()
model.segment_video( video_path= video_path, output_path="./", # Outputs will be saved as foreground.webm or foreground.mp4. The default value is "./" fps=0, # If this is set to 0 CV2 will detect the fps in the original video. The default value is 0. refine_foreground=False, #refine foreground is an extract postprocessing step that increases inference time but can improve matting edges. The default value is False. batch=1, # We recommended that batch size not exceed 3 for consumer GPUs as there are minimal inference gains. The default value is 1. print_frames_processed=True, #Informs you what frame is being processed. The default value is True. webm = False, # This will output an alpha layer video but this defaults to mp4 when webm is false. The default value is False. rgb_value= (0, 255, 0) # If you do not use webm this will be the RGB value of the resulting background only when webm is False. The default value is a green background (0,255,0). )
```
**# BEN2 evaluation**
RMBG 2.0 did not preserve the DIS 5k validation dataset
.gitattributes+6
BEN2_demo_pictures/grid_example1.pngAdded

Large File Pointer Details
- SHA256: 49df5808df57c1db87f1bdf94ff0687ba436f2c377378799dd3ce49be85e0973
- Pointer size: 132 Bytes
- Size of remote file: 1.51 MB
BEN2_demo_pictures/grid_example2.pngAdded

Large File Pointer Details
- SHA256: 0899c57bdb592ccf3b04ed0316d3f8d4b23f337ff00f6807b18b46b74b8e91bf
- Pointer size: 132 Bytes
- Size of remote file: 1.76 MB
BEN2_demo_pictures/grid_example3.pngAdded

Large File Pointer Details
- SHA256: f0e2cb53afd4ad04daa223525f688cad835826890eb4ababb1e0bf0e629800e5
- Pointer size: 132 Bytes
- Size of remote file: 8.59 MB
BEN2_demo_pictures/grid_example6.pngAdded

Large File Pointer Details
- SHA256: 327eca743beef0cd452e40015b0695d67806cd6b59bd3a7759cfd2be260c5cae
- Pointer size: 132 Bytes
- Size of remote file: 2.37 MB
BEN2_demo_pictures/grid_example7.pngAdded

Large File Pointer Details
- SHA256: 0f758d617b3266d2fb540bd5088c58a3a69d1cb5e54dcdf0a4d5ea6b74c6e7e2
- Pointer size: 132 Bytes
- Size of remote file: 5.27 MB
BEN2_demo_pictures/model_comparison.pngAdded

Large File Pointer Details
- SHA256: b7b666c9f0b2c40fa471c21a3eeb6ff34f045082b3253d05392c7c58caff8621
- Pointer size: 131 Bytes
- Size of remote file: 328 kB
README.mdAdded+226