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_mlx.py from JvasquezT/eraser: direct link, hf CLI and curl.
- Browser
- Download file 1.86 kB
-
https://huggingface.co/JvasquezT/eraser/resolve/main/examples/inference_mlx.py
- Command line
-
hf download hf://JvasquezT/eraser/examples/inference_mlx.py
-
curl -L -o inference_mlx.py https://huggingface.co/JvasquezT/eraser/resolve/main/examples/inference_mlx.py
1.86 kB
| """ | |
| Remove the background of an image with the MLX model. | |
| python -m pip install mlx numpy pillow | |
| python examples/inference_mlx.py photo.jpg # -> photo_cutout.png (RGBA) | |
| python examples/inference_mlx.py photo.jpg --model mlx/model_fp16.safetensors --mask photo_mask.png | |
| """ | |
| import argparse | |
| import sys | |
| from pathlib import Path | |
| import mlx.core as mx | |
| import numpy as np | |
| from PIL import Image, ImageOps | |
| if not __package__: # support running `python examples/inference_mlx.py` | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| from model_mlx import DEFAULT_WEIGHTS, load_model | |
| RES = 512 # fixed model resolution | |
| def remove_background(model, 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 = np.asarray(model(mx.array(x))[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", type=Path, default=DEFAULT_WEIGHTS) | |
| 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() | |
| model = load_model(args.model) | |
| with Image.open(args.image) as source: | |
| img = ImageOps.exif_transpose(source).convert("RGB") | |
| alpha = remove_background(model, 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) | |