neigui/anime-remove-background
0
1import gradio as gr2import huggingface_hub3import onnxruntime as rt4import numpy as np5import cv26 7 8def 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 - w13 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 mask22 23 24def 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, img31 32 33if __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 "\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 examples_data = [[f"examples/{x:02d}.jpg"] for x in range(1, 4)]46 examples = gr.Dataset(components=[input_img], samples=examples_data)47 run_btn = gr.Button(variant="primary")48 output_mask = gr.Image(label="mask")49 output_img = gr.Image(label="result", image_mode="RGBA")50 examples.click(lambda x: x[0], [examples], [input_img])51 run_btn.click(rmbg_fn, [input_img], [output_mask, output_img])52 app.launch()53 