yaoqi commited on
Commit
6681bc1
1 Parent(s): 00b01db

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -0
app.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import huggingface_hub
3
+ import onnxruntime as rt
4
+ import numpy as np
5
+ import cv2
6
+
7
+
8
+ def get_mask(img, s=1024):
9
+ img = (img / 255).astype(np.float32)
10
+ h, w = h0, w0 = img.shape[:-1]
11
+ h, w = (s, int(s * w / h)) if h > w else (int(s * h / w), s)
12
+ ph, pw = s - h, s - w
13
+ img_input = np.zeros([s, s, 3], dtype=np.float32)
14
+ img_input[ph // 2:ph // 2 + h, pw // 2:pw // 2 + w] = cv2.resize(img, (w, h))
15
+ img_input = np.transpose(img_input, (2, 0, 1))
16
+ img_input = img_input[np.newaxis, :]
17
+ mask = rmbg_model.run(None, {'img': img_input})[0][0]
18
+ mask = np.transpose(mask, (1, 2, 0))
19
+ mask = mask[ph // 2:ph // 2 + h, pw // 2:pw // 2 + w]
20
+ mask = cv2.resize(mask, (w0, h0))[:, :, np.newaxis]
21
+ return mask
22
+
23
+
24
+ def rmbg_fn(img):
25
+ mask = get_mask(img)
26
+ img = (mask * img + 255 * (1 - mask)).astype(np.uint8)
27
+ mask = (mask * 255).astype(np.uint8)
28
+ img = np.concatenate([img, mask], axis=2, dtype=np.uint8)
29
+ mask = mask.repeat(3, axis=2)
30
+ return mask, img
31
+
32
+
33
+ if __name__ == "__main__":
34
+ providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
35
+ model_path = huggingface_hub.hf_hub_download("skytnt/anime-seg", "isnetis.onnx")
36
+ rmbg_model = rt.InferenceSession(model_path, providers=providers)
37
+ app = gr.Blocks()
38
+ with app:
39
+ gr.Markdown("# Anime Remove Background\n\n"
40
+ "![visitor badge](https://visitor-badge.glitch.me/badge?page_id=skytnt.animeseg)\n\n"
41
+ "demo for [https://github.com/SkyTNT/anime-segmentation/](https://github.com/SkyTNT/anime-segmentation/)")
42
+ with gr.Row():
43
+ with gr.Column():
44
+ input_img = gr.Image(label="input image")
45
+ run_btn = gr.Button(variant="primary")
46
+ output_mask = gr.Image(label="mask")
47
+ output_img = gr.Image(label="result", image_mode="RGBA")
48
+ run_btn.click(rmbg_fn, [input_img], [output_mask, output_img])
49
+ app.launch()