Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
from torchvision.transforms.functional import to_tensor, to_pil_image
|
4 |
+
from PIL import Image
|
5 |
+
import cv2
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
# Load AnimeGANv2 pretrained generator (e.g., "hayao")
|
9 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
10 |
+
anime_model = torch.hub.load(
|
11 |
+
"bryandlee/animegan2-pytorch:main",
|
12 |
+
"generator",
|
13 |
+
pretrained="hayao", # options: "hayao", "paprika", "face_paint_v1", "face_paint_v2"
|
14 |
+
).to(device).eval()
|
15 |
+
|
16 |
+
def apply_animegan(img: np.ndarray) -> np.ndarray:
|
17 |
+
pil = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
|
18 |
+
tensor = to_tensor(pil).unsqueeze(0).mul(2).sub(1).to(device) # [-1,1]
|
19 |
+
with torch.no_grad():
|
20 |
+
out = anime_model(tensor)[0]
|
21 |
+
out = out.clamp(-1, 1).add(1).div(2)
|
22 |
+
pil_out = to_pil_image(out.cpu())
|
23 |
+
return cv2.cvtColor(np.array(pil_out), cv2.COLOR_RGB2BGR)
|
24 |
+
|
25 |
+
def apply_cartoon_filter(img: np.ndarray) -> np.ndarray:
|
26 |
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
27 |
+
gray = cv2.medianBlur(gray, 5)
|
28 |
+
edges = cv2.adaptiveThreshold(gray, 255,
|
29 |
+
cv2.ADAPTIVE_THRESH_MEAN_C,
|
30 |
+
cv2.THRESH_BINARY, 9, 9)
|
31 |
+
color = cv2.bilateralFilter(img, 9, 300, 300)
|
32 |
+
return cv2.bitwise_and(color, color, mask=edges)
|
33 |
+
|
34 |
+
def cartoonizer(input_img, style):
|
35 |
+
img = cv2.cvtColor(np.array(input_img), cv2.COLOR_RGB2BGR)
|
36 |
+
if style == "Cartoon Filter":
|
37 |
+
out = apply_cartoon_filter(img)
|
38 |
+
elif style == "AnimeGANv2 (Hayao)":
|
39 |
+
out = apply_animegan(img)
|
40 |
+
else:
|
41 |
+
out = img
|
42 |
+
return Image.fromarray(cv2.cvtColor(out, cv2.COLOR_BGR2RGB))
|
43 |
+
|
44 |
+
gr.Interface(
|
45 |
+
fn=cartoonizer,
|
46 |
+
inputs=[
|
47 |
+
gr.Image(type="pil", label="Upload Image"),
|
48 |
+
gr.Radio(["Cartoon Filter", "AnimeGANv2 (Hayao)"], label="Style")
|
49 |
+
],
|
50 |
+
outputs=gr.Image(type="pil", label="Cartoonized Output"),
|
51 |
+
title="🎨 Cartoonizer with AnimeGANv2",
|
52 |
+
description="Upload any image and convert to general cartoon or Hayao‑style anime."
|
53 |
+
).launch()
|