Image Segmentation
ONNX
Safetensors
MLX
background-removal
image-matting
knowledge-distillation
lightweight
Instructions to use JvasquezT/eraser with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use JvasquezT/eraser with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] hf download JvasquezT/eraser --local-dir eraser
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
Download examples/inference.py from JvasquezT/eraser: direct link, hf CLI and curl.
- Browser
- Download file 1.71 kB
-
https://huggingface.co/JvasquezT/eraser/resolve/main/examples/inference.py
- Command line
-
hf download hf://JvasquezT/eraser/examples/inference.py
-
curl -L -o inference.py https://huggingface.co/JvasquezT/eraser/resolve/main/examples/inference.py
1.71 kB
| """ | |
| Remove the background of an image with the ONNX model. | |
| pip install onnxruntime numpy pillow | |
| python inference.py photo.jpg # -> photo_cutout.png (RGBA) | |
| python inference.py photo.jpg --model ../onnx/model_int8.onnx --mask photo_mask.png | |
| """ | |
| import argparse | |
| from pathlib import Path | |
| import numpy as np | |
| import onnxruntime as ort | |
| from PIL import Image, ImageOps | |
| RES = 512 # fixed model resolution | |
| def remove_background(session, img): | |
| """img: PIL RGB -> PIL 'L' alpha of the same size as img.""" | |
| w, h = img.size | |
| x = np.asarray(img.resize((RES, RES), Image.BILINEAR), dtype=np.float32).transpose(2, 0, 1)[None] / 255 | |
| alpha = session.run(None, {"image": x})[0][0, 0] # (512, 512) in [0, 1] | |
| alpha = Image.fromarray((alpha * 255).clip(0, 255).astype("uint8")) | |
| return alpha.resize((w, h), Image.BILINEAR) | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("image") | |
| ap.add_argument("--model", default=str(Path(__file__).parent.parent / "onnx" / "model.onnx")) | |
| ap.add_argument("--out", help="output RGBA PNG (default: <image>_cutout.png)") | |
| ap.add_argument("--mask", help="if given, also save the alpha mask to this PNG") | |
| args = ap.parse_args() | |
| session = ort.InferenceSession(args.model, providers=["CPUExecutionProvider"]) | |
| img = ImageOps.exif_transpose(Image.open(args.image)).convert("RGB") | |
| alpha = remove_background(session, img) | |
| out = Path(args.out) if args.out else Path(args.image).with_name(Path(args.image).stem + "_cutout.png") | |
| cut = img.copy() | |
| cut.putalpha(alpha) | |
| cut.save(out) | |
| if args.mask: | |
| alpha.save(args.mask) | |
| print("saved", out) | |