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