File size: 1,714 Bytes
72e7070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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)