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