maxorange commited on
Commit
0cdce13
·
verified ·
1 Parent(s): faf13d4
Files changed (3) hide show
  1. app.py +119 -0
  2. packages.txt +3 -0
  3. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import gradio as gr
3
+ import numpy as np
4
+ import onnxruntime
5
+ import requests
6
+ from huggingface_hub import hf_hub_download
7
+ from PIL import Image
8
+ from rembg import remove
9
+
10
+
11
+ # Get x_scale_factor & y_scale_factor to resize image
12
+ def get_scale_factor(im_h, im_w, ref_size=512):
13
+
14
+ if max(im_h, im_w) < ref_size or min(im_h, im_w) > ref_size:
15
+ if im_w >= im_h:
16
+ im_rh = ref_size
17
+ im_rw = int(im_w / im_h * ref_size)
18
+ elif im_w < im_h:
19
+ im_rw = ref_size
20
+ im_rh = int(im_h / im_w * ref_size)
21
+ else:
22
+ im_rh = im_h
23
+ im_rw = im_w
24
+
25
+ im_rw = im_rw - im_rw % 32
26
+ im_rh = im_rh - im_rh % 32
27
+
28
+ x_scale_factor = im_rw / im_w
29
+ y_scale_factor = im_rh / im_h
30
+
31
+ return x_scale_factor, y_scale_factor
32
+
33
+
34
+ MODEL_PATH = hf_hub_download('nateraw/background-remover-files', 'modnet.onnx', repo_type='dataset')
35
+
36
+
37
+ def main(image_path, threshold):
38
+
39
+ # read image
40
+ im = cv2.imread(image_path)
41
+ im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
42
+
43
+ # unify image channels to 3
44
+ if len(im.shape) == 2:
45
+ im = im[:, :, None]
46
+ if im.shape[2] == 1:
47
+ im = np.repeat(im, 3, axis=2)
48
+ elif im.shape[2] == 4:
49
+ im = im[:, :, 0:3]
50
+
51
+ # normalize values to scale it between -1 to 1
52
+ im = (im - 127.5) / 127.5
53
+
54
+ im_h, im_w, im_c = im.shape
55
+ x, y = get_scale_factor(im_h, im_w)
56
+
57
+ # resize image
58
+ im = cv2.resize(im, None, fx=x, fy=y, interpolation=cv2.INTER_AREA)
59
+
60
+ # prepare input shape
61
+ im = np.transpose(im)
62
+ im = np.swapaxes(im, 1, 2)
63
+ im = np.expand_dims(im, axis=0).astype('float32')
64
+
65
+ # Initialize session and get prediction
66
+ session = onnxruntime.InferenceSession(MODEL_PATH, None)
67
+ input_name = session.get_inputs()[0].name
68
+ output_name = session.get_outputs()[0].name
69
+ result = session.run([output_name], {input_name: im})
70
+
71
+ # refine matte
72
+ matte = (np.squeeze(result[0]) * 255).astype('uint8')
73
+ matte = cv2.resize(matte, dsize=(im_w, im_h), interpolation=cv2.INTER_AREA)
74
+
75
+ # HACK - Could probably just convert this to PIL instead of writing
76
+ cv2.imwrite('out.png', matte)
77
+
78
+ image = Image.open(image_path)
79
+ matte = Image.open('out.png')
80
+
81
+ # obtain predicted foreground
82
+ image = np.asarray(image)
83
+ if len(image.shape) == 2:
84
+ image = image[:, :, None]
85
+ if image.shape[2] == 1:
86
+ image = np.repeat(image, 3, axis=2)
87
+ elif image.shape[2] == 4:
88
+ image = image[:, :, 0:3]
89
+
90
+ b, g, r = cv2.split(image)
91
+
92
+ mask = np.asarray(matte)
93
+ a = np.ones(mask.shape, dtype='uint8') * 255
94
+ alpha_im = cv2.merge([b, g, r, a], 4)
95
+ bg = np.zeros(alpha_im.shape)
96
+ new_mask = np.stack([mask, mask, mask, mask], axis=2)
97
+ foreground = np.where(new_mask > threshold, alpha_im, bg).astype(np.uint8)
98
+
99
+ bg_remove1 = Image.fromarray(foreground) # Variant 1
100
+ bg_remove2 = remove(Image.open(image_path)) # Variant 2
101
+ return [bg_remove1, bg_remove2]
102
+
103
+
104
+ title = "MODNet Background Remover"
105
+ description = "Gradio demo for MODNet, a model that can remove the background from a given image. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below."
106
+ article = "<div style='text-align: center;'> <a href='https://github.com/ZHKKKe/MODNet' target='_blank'>Github Repo</a> | <a href='https://arxiv.org/abs/2011.11961' target='_blank'>MODNet: Real-Time Trimap-Free Portrait Matting via Objective Decomposition</a> </div>"
107
+
108
+ interface = gr.Interface(
109
+ fn=main,
110
+ inputs=[
111
+ gr.Image(type='filepath'),
112
+ gr.Slider(minimum=0, maximum=250, value=100, step=5, label='Mask Cutoff Threshold'),
113
+ ],
114
+ outputs=gr.Gallery(format="png"),
115
+ title=title,
116
+ description=description,
117
+ article=article,
118
+ flagging_mode="never",
119
+ ).queue().launch(show_error=True)
packages.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ffmpeg
2
+ libsm6
3
+ libxext6
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ onnxruntime
2
+ onnx
3
+ opencv-python
4
+ numpy
5
+ huggingface_hub
6
+ rembg