Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import spaces
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from torchvision import transforms
|
| 6 |
+
from transformers import AutoModelForImageSegmentation
|
| 7 |
+
|
| 8 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 9 |
+
model = AutoModelForImageSegmentation.from_pretrained(
|
| 10 |
+
'joelseytre/toonout', trust_remote_code=True
|
| 11 |
+
).eval().to(device)
|
| 12 |
+
|
| 13 |
+
@spaces.GPU
|
| 14 |
+
def remove_background(image, resolution="1024x1024"):
|
| 15 |
+
if image is None:
|
| 16 |
+
return None
|
| 17 |
+
|
| 18 |
+
res = int(resolution.split('x')[0])
|
| 19 |
+
if image.mode != 'RGB':
|
| 20 |
+
image = image.convert('RGB')
|
| 21 |
+
|
| 22 |
+
original_size = image.size
|
| 23 |
+
transform = transforms.Compose([
|
| 24 |
+
transforms.Resize((res, res)),
|
| 25 |
+
transforms.ToTensor(),
|
| 26 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 27 |
+
])
|
| 28 |
+
|
| 29 |
+
input_tensor = transform(image).unsqueeze(0).to(device)
|
| 30 |
+
|
| 31 |
+
with torch.no_grad():
|
| 32 |
+
preds = model(input_tensor)[-1].sigmoid().cpu()
|
| 33 |
+
|
| 34 |
+
pred = preds[0].squeeze()
|
| 35 |
+
mask = transforms.ToPILImage()(pred).resize(original_size)
|
| 36 |
+
|
| 37 |
+
output = image.copy()
|
| 38 |
+
output.putalpha(mask)
|
| 39 |
+
return output
|
| 40 |
+
|
| 41 |
+
demo = gr.Interface(
|
| 42 |
+
fn=remove_background,
|
| 43 |
+
inputs=[
|
| 44 |
+
gr.Image(type="pil", label="Upload Image"),
|
| 45 |
+
gr.Dropdown(["512x512", "1024x1024", "2048x2048"], value="1024x1024", label="Resolution")
|
| 46 |
+
],
|
| 47 |
+
outputs=gr.Image(type="pil", label="Result"),
|
| 48 |
+
title="ToonOut - Anime Background Removal",
|
| 49 |
+
description="99.5% accuracy on anime/cartoon images. MIT License - free for commercial use."
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
demo.launch()
|