File size: 1,856 Bytes
c6b517a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
46
47
48
49
50
51
52
53
"""
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)