Update app.py
Browse files
app.py
CHANGED
|
@@ -5,18 +5,8 @@ import gradio as gr
|
|
| 5 |
from PIL import Image, ImageFilter, ImageOps, ImageChops
|
| 6 |
import torchvision.transforms as transforms
|
| 7 |
import os
|
| 8 |
-
import random
|
| 9 |
-
import pathlib
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
# Create a directory to save output images
|
| 13 |
-
output_dir = "outputs"
|
| 14 |
-
os.makedirs(output_dir, exist_ok=True)
|
| 15 |
-
|
| 16 |
-
# Define allowed image extensions for the file explorer
|
| 17 |
-
IMAGE_EXTENSIONS = [".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tiff"]
|
| 18 |
-
|
| 19 |
-
# --- 🎨 Filters ---
|
| 20 |
FILTERS = {
|
| 21 |
"Standard": "📄", "Invert": "⚫⚪", "Blur": "🌫️", "Sharpen": "🔪", "Contour": "🗺️",
|
| 22 |
"Detail": "🔍", "EdgeEnhance": "📏", "EdgeEnhanceMore": "📐", "Emboss": "🏞️",
|
|
@@ -34,50 +24,99 @@ FILTERS = {
|
|
| 34 |
"HardLight": "🔦", "Binary": "🌓", "Noise": "❄️"
|
| 35 |
}
|
| 36 |
|
| 37 |
-
#
|
| 38 |
norm_layer = nn.InstanceNorm2d
|
|
|
|
|
|
|
| 39 |
class ResidualBlock(nn.Module):
|
| 40 |
def __init__(self, in_features):
|
| 41 |
super(ResidualBlock, self).__init__()
|
| 42 |
-
conv_block = [ nn.ReflectionPad2d(1),
|
| 43 |
-
nn.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
self.conv_block = nn.Sequential(*conv_block)
|
| 45 |
-
def forward(self, x): return x + self.conv_block(x)
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
class Generator(nn.Module):
|
| 48 |
def __init__(self, input_nc, output_nc, n_residual_blocks=9, sigmoid=True):
|
| 49 |
super(Generator, self).__init__()
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
self.model0 = nn.Sequential(*model0)
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
| 53 |
for _ in range(2):
|
| 54 |
-
model1 += [
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
| 56 |
self.model1 = nn.Sequential(*model1)
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
| 58 |
self.model2 = nn.Sequential(*model2)
|
| 59 |
-
|
|
|
|
|
|
|
| 60 |
for _ in range(2):
|
| 61 |
-
model3 += [
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
| 63 |
self.model3 = nn.Sequential(*model3)
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
| 66 |
self.model4 = nn.Sequential(*model4)
|
| 67 |
-
def forward(self, x, cond=None): return self.model4(self.model3(self.model2(self.model1(self.model0(x)))))
|
| 68 |
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
try:
|
| 71 |
-
model1 = Generator(3, 1, 3)
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
except FileNotFoundError:
|
| 74 |
-
print("
|
| 75 |
model1, model2 = None, None
|
| 76 |
|
| 77 |
-
#
|
| 78 |
def apply_filter(line_img, filter_name, original_img):
|
| 79 |
-
if filter_name == "Standard":
|
|
|
|
|
|
|
|
|
|
| 80 |
line_img_l = line_img.convert('L')
|
|
|
|
|
|
|
| 81 |
if filter_name == "Invert": return ImageOps.invert(line_img_l)
|
| 82 |
if filter_name == "Blur": return line_img.filter(ImageFilter.GaussianBlur(radius=3))
|
| 83 |
if filter_name == "Sharpen": return line_img.filter(ImageFilter.SHARPEN)
|
|
@@ -89,37 +128,68 @@ def apply_filter(line_img, filter_name, original_img):
|
|
| 89 |
if filter_name == "FindEdges": return line_img_l.filter(ImageFilter.FIND_EDGES)
|
| 90 |
if filter_name == "Smooth": return line_img.filter(ImageFilter.SMOOTH)
|
| 91 |
if filter_name == "SmoothMore": return line_img.filter(ImageFilter.SMOOTH_MORE)
|
|
|
|
|
|
|
| 92 |
if filter_name == "Solarize": return ImageOps.solarize(line_img_l)
|
| 93 |
-
if filter_name
|
|
|
|
|
|
|
|
|
|
| 94 |
if filter_name == "Equalize": return ImageOps.equalize(line_img_l)
|
| 95 |
if filter_name == "AutoContrast": return ImageOps.autocontrast(line_img_l)
|
| 96 |
if filter_name == "Binary": return line_img_l.convert('1')
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
colors_on_white = {"RedOnWhite": "red", "OrangeOnWhite": "orange", "YellowOnWhite": "yellow", "GreenOnWhite": "green", "BlueOnWhite": "blue", "PurpleOnWhite": "purple", "PinkOnWhite": "pink", "CyanOnWhite": "cyan", "MagentaOnWhite": "magenta", "BrownOnWhite": "brown", "GrayOnWhite": "gray"}
|
| 100 |
-
if filter_name in colors_on_white:
|
|
|
|
|
|
|
|
|
|
| 101 |
colors_on_black = {"WhiteOnBlack": "white", "RedOnBlack": "red", "OrangeOnBlack": "orange", "YellowOnBlack": "yellow", "GreenOnBlack": "green", "BlueOnBlack": "blue", "PurpleOnBlack": "purple", "PinkOnBlack": "pink", "CyanOnBlack": "cyan", "MagentaOnBlack": "magenta", "BrownOnBlack": "brown", "GrayOnBlack": "gray"}
|
| 102 |
-
if filter_name in colors_on_black:
|
|
|
|
|
|
|
|
|
|
| 103 |
line_img_rgb = line_img.convert('RGB')
|
| 104 |
-
|
| 105 |
-
if filter_name
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
if filter_name == "Noise":
|
| 107 |
-
img_array = np.array(line_img_l)
|
| 108 |
noise = np.random.randint(-20, 20, img_array.shape, dtype='int16')
|
| 109 |
noisy_array = np.clip(img_array.astype('int16') + noise, 0, 255).astype('uint8')
|
| 110 |
return Image.fromarray(noisy_array)
|
| 111 |
-
return line_img
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
|
|
|
|
|
|
| 115 |
if not model1 or not model2:
|
| 116 |
raise gr.Error("Models are not loaded. Please check for 'model.pth' and 'model2.pth'.")
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
filter_name = filter_choice.split(" ", 1)[1]
|
|
|
|
| 121 |
original_img = Image.open(input_img_path).convert('RGB')
|
| 122 |
-
|
|
|
|
| 123 |
transform = transforms.Compose([
|
| 124 |
transforms.Resize(256, transforms.InterpolationMode.BICUBIC),
|
| 125 |
transforms.ToTensor(),
|
|
@@ -128,117 +198,55 @@ def process_image(input_img_path, line_style, filter_choice, gallery_state):
|
|
| 128 |
input_tensor = transform(original_img).unsqueeze(0)
|
| 129 |
|
| 130 |
with torch.no_grad():
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
| 132 |
|
|
|
|
| 133 |
line_drawing_low_res = transforms.ToPILImage()(output.squeeze().cpu().clamp(0, 1))
|
| 134 |
-
line_drawing_full_res = line_drawing_low_res.resize(original_img.size, Image.Resampling.BICUBIC)
|
| 135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
final_image = apply_filter(line_drawing_full_res, filter_name, original_img)
|
| 137 |
-
|
| 138 |
-
# --- 💾 Save the output and update gallery state ---
|
| 139 |
-
base_name = pathlib.Path(input_img_path).stem
|
| 140 |
-
output_filename = f"{base_name}_{filter_name}.png"
|
| 141 |
-
output_filepath = os.path.join(output_dir, output_filename)
|
| 142 |
-
final_image.save(output_filepath)
|
| 143 |
-
|
| 144 |
-
# Add new image path to the beginning of the list
|
| 145 |
-
gallery_state.insert(0, output_filepath)
|
| 146 |
|
| 147 |
-
|
| 148 |
-
return final_image, gallery_state
|
| 149 |
|
| 150 |
-
#
|
| 151 |
title = "🖌️ Image to Line Art with Creative Filters"
|
| 152 |
-
description = "
|
| 153 |
-
|
| 154 |
-
#
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
gr.Markdown("### 1. Select an Image")
|
| 184 |
-
# File explorer for a better user experience
|
| 185 |
-
input_image_path = gr.FileExplorer(
|
| 186 |
-
root=".",
|
| 187 |
-
glob=f"**/*[{''.join(ext[1:] for ext in IMAGE_EXTENSIONS)}]",
|
| 188 |
-
label="Browse Your Images",
|
| 189 |
-
height=400
|
| 190 |
-
)
|
| 191 |
-
gr.Markdown("### 2. Choose a Line Style")
|
| 192 |
-
line_style_radio = gr.Radio(
|
| 193 |
-
['Complex Lines', 'Simple Lines'],
|
| 194 |
-
label="Line Style",
|
| 195 |
-
value='Simple Lines'
|
| 196 |
-
)
|
| 197 |
-
|
| 198 |
-
with gr.Column(scale=3):
|
| 199 |
-
gr.Markdown("### 3. Pick a Filter")
|
| 200 |
-
filter_buttons = [gr.Button(value=f"{emoji} {name}") for name, emoji in FILTERS.items()]
|
| 201 |
-
|
| 202 |
-
# Hidden radio to store the selected button's value
|
| 203 |
-
selected_filter = gr.Radio(
|
| 204 |
-
[b.value for b in filter_buttons],
|
| 205 |
-
label="Selected Filter",
|
| 206 |
-
visible=False,
|
| 207 |
-
value=filter_buttons[0].value
|
| 208 |
-
)
|
| 209 |
-
|
| 210 |
-
gr.Markdown("### 4. Result")
|
| 211 |
-
main_output_image = gr.Image(type="pil", label="Latest Result")
|
| 212 |
-
|
| 213 |
-
with gr.Row():
|
| 214 |
-
gr.Markdown("---")
|
| 215 |
-
|
| 216 |
-
with gr.Row():
|
| 217 |
-
# --- Dynamic Examples ---
|
| 218 |
-
gr.Examples(
|
| 219 |
-
examples=generate_examples(),
|
| 220 |
-
inputs=[input_image_path, line_style_radio, selected_filter],
|
| 221 |
-
label="✨ Click an Example to Start",
|
| 222 |
-
examples_per_page=10
|
| 223 |
-
)
|
| 224 |
-
|
| 225 |
-
with gr.Row():
|
| 226 |
-
gr.Markdown("## 🖼️ Result Gallery (Saved in 'outputs' folder)")
|
| 227 |
-
gallery_output = gr.Gallery(label="Your Generated Images", height=600, columns=5)
|
| 228 |
-
|
| 229 |
-
# --- Event Handling ---
|
| 230 |
-
def handle_filter_click(btn_value, current_path, style, state):
|
| 231 |
-
# When a filter button is clicked, it triggers the main processing function
|
| 232 |
-
new_main_img, new_state = process_image(current_path, style, btn_value, state)
|
| 233 |
-
# Update the hidden radio, the main image, and the gallery
|
| 234 |
-
return btn_value, new_main_img, new_state
|
| 235 |
-
|
| 236 |
-
for btn in filter_buttons:
|
| 237 |
-
btn.click(
|
| 238 |
-
fn=handle_filter_click,
|
| 239 |
-
inputs=[btn, input_image_path, line_style_radio, gallery_state],
|
| 240 |
-
outputs=[selected_filter, main_output_image, gallery_state]
|
| 241 |
-
)
|
| 242 |
|
| 243 |
if __name__ == "__main__":
|
| 244 |
-
|
|
|
|
| 5 |
from PIL import Image, ImageFilter, ImageOps, ImageChops
|
| 6 |
import torchvision.transforms as transforms
|
| 7 |
import os
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# 🎨 Dictionary of all filters with their corresponding emojis
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
FILTERS = {
|
| 11 |
"Standard": "📄", "Invert": "⚫⚪", "Blur": "🌫️", "Sharpen": "🔪", "Contour": "🗺️",
|
| 12 |
"Detail": "🔍", "EdgeEnhance": "📏", "EdgeEnhanceMore": "📐", "Emboss": "🏞️",
|
|
|
|
| 24 |
"HardLight": "🔦", "Binary": "🌓", "Noise": "❄️"
|
| 25 |
}
|
| 26 |
|
| 27 |
+
# 🧠 Neural network layers
|
| 28 |
norm_layer = nn.InstanceNorm2d
|
| 29 |
+
|
| 30 |
+
# 🧱 Building block for the generator
|
| 31 |
class ResidualBlock(nn.Module):
|
| 32 |
def __init__(self, in_features):
|
| 33 |
super(ResidualBlock, self).__init__()
|
| 34 |
+
conv_block = [ nn.ReflectionPad2d(1),
|
| 35 |
+
nn.Conv2d(in_features, in_features, 3),
|
| 36 |
+
norm_layer(in_features),
|
| 37 |
+
nn.ReLU(inplace=True),
|
| 38 |
+
nn.ReflectionPad2d(1),
|
| 39 |
+
nn.Conv2d(in_features, in_features, 3),
|
| 40 |
+
norm_layer(in_features) ]
|
| 41 |
self.conv_block = nn.Sequential(*conv_block)
|
|
|
|
| 42 |
|
| 43 |
+
def forward(self, x):
|
| 44 |
+
return x + self.conv_block(x)
|
| 45 |
+
|
| 46 |
+
# 🎨 Generator model for creating line drawings
|
| 47 |
class Generator(nn.Module):
|
| 48 |
def __init__(self, input_nc, output_nc, n_residual_blocks=9, sigmoid=True):
|
| 49 |
super(Generator, self).__init__()
|
| 50 |
+
# Initial convolution block
|
| 51 |
+
model0 = [ nn.ReflectionPad2d(3),
|
| 52 |
+
nn.Conv2d(input_nc, 64, 7),
|
| 53 |
+
norm_layer(64),
|
| 54 |
+
nn.ReLU(inplace=True) ]
|
| 55 |
self.model0 = nn.Sequential(*model0)
|
| 56 |
+
# Downsampling
|
| 57 |
+
model1 = []
|
| 58 |
+
in_features = 64
|
| 59 |
+
out_features = in_features*2
|
| 60 |
for _ in range(2):
|
| 61 |
+
model1 += [ nn.Conv2d(in_features, out_features, 3, stride=2, padding=1),
|
| 62 |
+
norm_layer(out_features),
|
| 63 |
+
nn.ReLU(inplace=True) ]
|
| 64 |
+
in_features = out_features
|
| 65 |
+
out_features = in_features*2
|
| 66 |
self.model1 = nn.Sequential(*model1)
|
| 67 |
+
# Residual blocks
|
| 68 |
+
model2 = []
|
| 69 |
+
for _ in range(n_residual_blocks):
|
| 70 |
+
model2 += [ResidualBlock(in_features)]
|
| 71 |
self.model2 = nn.Sequential(*model2)
|
| 72 |
+
# Upsampling
|
| 73 |
+
model3 = []
|
| 74 |
+
out_features = in_features//2
|
| 75 |
for _ in range(2):
|
| 76 |
+
model3 += [ nn.ConvTranspose2d(in_features, out_features, 3, stride=2, padding=1, output_padding=1),
|
| 77 |
+
norm_layer(out_features),
|
| 78 |
+
nn.ReLU(inplace=True) ]
|
| 79 |
+
in_features = out_features
|
| 80 |
+
out_features = in_features//2
|
| 81 |
self.model3 = nn.Sequential(*model3)
|
| 82 |
+
# Output layer
|
| 83 |
+
model4 = [ nn.ReflectionPad2d(3),
|
| 84 |
+
nn.Conv2d(64, output_nc, 7)]
|
| 85 |
+
if sigmoid:
|
| 86 |
+
model4 += [nn.Sigmoid()]
|
| 87 |
self.model4 = nn.Sequential(*model4)
|
|
|
|
| 88 |
|
| 89 |
+
def forward(self, x, cond=None):
|
| 90 |
+
out = self.model0(x)
|
| 91 |
+
out = self.model1(out)
|
| 92 |
+
out = self.model2(out)
|
| 93 |
+
out = self.model3(out)
|
| 94 |
+
out = self.model4(out)
|
| 95 |
+
return out
|
| 96 |
+
|
| 97 |
+
# 🔧 Load the models
|
| 98 |
+
# Make sure you have 'model.pth' and 'model2.pth' in the same directory
|
| 99 |
try:
|
| 100 |
+
model1 = Generator(3, 1, 3)
|
| 101 |
+
model1.load_state_dict(torch.load('model.pth', map_location=torch.device('cpu')))
|
| 102 |
+
model1.eval()
|
| 103 |
+
|
| 104 |
+
model2 = Generator(3, 1, 3)
|
| 105 |
+
model2.load_state_dict(torch.load('model2.pth', map_location=torch.device('cpu')))
|
| 106 |
+
model2.eval()
|
| 107 |
except FileNotFoundError:
|
| 108 |
+
print("Warning: Model files 'model.pth' or 'model2.pth' not found. The application will not run correctly.")
|
| 109 |
model1, model2 = None, None
|
| 110 |
|
| 111 |
+
# ✨ Function to apply the selected filter
|
| 112 |
def apply_filter(line_img, filter_name, original_img):
|
| 113 |
+
if filter_name == "Standard":
|
| 114 |
+
return line_img
|
| 115 |
+
|
| 116 |
+
# Convert line drawing to grayscale for most operations
|
| 117 |
line_img_l = line_img.convert('L')
|
| 118 |
+
|
| 119 |
+
# --- Standard Image Filters ---
|
| 120 |
if filter_name == "Invert": return ImageOps.invert(line_img_l)
|
| 121 |
if filter_name == "Blur": return line_img.filter(ImageFilter.GaussianBlur(radius=3))
|
| 122 |
if filter_name == "Sharpen": return line_img.filter(ImageFilter.SHARPEN)
|
|
|
|
| 128 |
if filter_name == "FindEdges": return line_img_l.filter(ImageFilter.FIND_EDGES)
|
| 129 |
if filter_name == "Smooth": return line_img.filter(ImageFilter.SMOOTH)
|
| 130 |
if filter_name == "SmoothMore": return line_img.filter(ImageFilter.SMOOTH_MORE)
|
| 131 |
+
|
| 132 |
+
# --- Tonal Adjustments ---
|
| 133 |
if filter_name == "Solarize": return ImageOps.solarize(line_img_l)
|
| 134 |
+
if filter_name == "Posterize1": return ImageOps.posterize(line_img_l, 1)
|
| 135 |
+
if filter_name == "Posterize2": return ImageOps.posterize(line_img_l, 2)
|
| 136 |
+
if filter_name == "Posterize3": return ImageOps.posterize(line_img_l, 3)
|
| 137 |
+
if filter_name == "Posterize4": return ImageOps.posterize(line_img_l, 4)
|
| 138 |
if filter_name == "Equalize": return ImageOps.equalize(line_img_l)
|
| 139 |
if filter_name == "AutoContrast": return ImageOps.autocontrast(line_img_l)
|
| 140 |
if filter_name == "Binary": return line_img_l.convert('1')
|
| 141 |
+
|
| 142 |
+
# --- Morphological Operations (Thick/Thin) ---
|
| 143 |
+
if filter_name == "Thick1": return line_img_l.filter(ImageFilter.MinFilter(3))
|
| 144 |
+
if filter_name == "Thick2": return line_img_l.filter(ImageFilter.MinFilter(5))
|
| 145 |
+
if filter_name == "Thick3": return line_img_l.filter(ImageFilter.MinFilter(7))
|
| 146 |
+
if filter_name == "Thin1": return line_img_l.filter(ImageFilter.MaxFilter(3))
|
| 147 |
+
if filter_name == "Thin2": return line_img_l.filter(ImageFilter.MaxFilter(5))
|
| 148 |
+
if filter_name == "Thin3": return line_img_l.filter(ImageFilter.MaxFilter(7))
|
| 149 |
+
|
| 150 |
+
# --- Colorization (On White Background) ---
|
| 151 |
colors_on_white = {"RedOnWhite": "red", "OrangeOnWhite": "orange", "YellowOnWhite": "yellow", "GreenOnWhite": "green", "BlueOnWhite": "blue", "PurpleOnWhite": "purple", "PinkOnWhite": "pink", "CyanOnWhite": "cyan", "MagentaOnWhite": "magenta", "BrownOnWhite": "brown", "GrayOnWhite": "gray"}
|
| 152 |
+
if filter_name in colors_on_white:
|
| 153 |
+
return ImageOps.colorize(line_img_l, black=colors_on_white[filter_name], white="white")
|
| 154 |
+
|
| 155 |
+
# --- Colorization (On Black Background) ---
|
| 156 |
colors_on_black = {"WhiteOnBlack": "white", "RedOnBlack": "red", "OrangeOnBlack": "orange", "YellowOnBlack": "yellow", "GreenOnBlack": "green", "BlueOnBlack": "blue", "PurpleOnBlack": "purple", "PinkOnBlack": "pink", "CyanOnBlack": "cyan", "MagentaOnBlack": "magenta", "BrownOnBlack": "brown", "GrayOnBlack": "gray"}
|
| 157 |
+
if filter_name in colors_on_black:
|
| 158 |
+
return ImageOps.colorize(line_img_l, black=colors_on_black[filter_name], white="black")
|
| 159 |
+
|
| 160 |
+
# --- Blending Modes with Original Image ---
|
| 161 |
line_img_rgb = line_img.convert('RGB')
|
| 162 |
+
if filter_name == "Multiply": return ImageChops.multiply(original_img, line_img_rgb)
|
| 163 |
+
if filter_name == "Screen": return ImageChops.screen(original_img, line_img_rgb)
|
| 164 |
+
if filter_name == "Overlay": return ImageChops.overlay(original_img, line_img_rgb)
|
| 165 |
+
if filter_name == "Add": return ImageChops.add(original_img, line_img_rgb)
|
| 166 |
+
if filter_name == "Subtract": return ImageChops.subtract(original_img, line_img_rgb)
|
| 167 |
+
if filter_name == "Difference": return ImageChops.difference(original_img, line_img_rgb)
|
| 168 |
+
if filter_name == "Darker": return ImageChops.darker(original_img, line_img_rgb)
|
| 169 |
+
if filter_name == "Lighter": return ImageChops.lighter(original_img, line_img_rgb)
|
| 170 |
+
if filter_name == "SoftLight": return ImageChops.soft_light(original_img, line_img_rgb)
|
| 171 |
+
if filter_name == "HardLight": return ImageChops.hard_light(original_img, line_img_rgb)
|
| 172 |
+
|
| 173 |
+
# --- Texture ---
|
| 174 |
if filter_name == "Noise":
|
| 175 |
+
img_array = np.array(line_img_l.convert('L'))
|
| 176 |
noise = np.random.randint(-20, 20, img_array.shape, dtype='int16')
|
| 177 |
noisy_array = np.clip(img_array.astype('int16') + noise, 0, 255).astype('uint8')
|
| 178 |
return Image.fromarray(noisy_array)
|
|
|
|
| 179 |
|
| 180 |
+
return line_img # Default fallback
|
| 181 |
+
|
| 182 |
+
# 🖼️ Main function to process the image
|
| 183 |
+
def predict(input_img_path, line_style, filter_choice):
|
| 184 |
if not model1 or not model2:
|
| 185 |
raise gr.Error("Models are not loaded. Please check for 'model.pth' and 'model2.pth'.")
|
| 186 |
+
|
| 187 |
+
# Extract the filter name from the dropdown choice (e.g., "📄 Standard" -> "Standard")
|
|
|
|
| 188 |
filter_name = filter_choice.split(" ", 1)[1]
|
| 189 |
+
|
| 190 |
original_img = Image.open(input_img_path).convert('RGB')
|
| 191 |
+
original_size = original_img.size
|
| 192 |
+
|
| 193 |
transform = transforms.Compose([
|
| 194 |
transforms.Resize(256, transforms.InterpolationMode.BICUBIC),
|
| 195 |
transforms.ToTensor(),
|
|
|
|
| 198 |
input_tensor = transform(original_img).unsqueeze(0)
|
| 199 |
|
| 200 |
with torch.no_grad():
|
| 201 |
+
if line_style == 'Simple Lines':
|
| 202 |
+
output = model2(input_tensor)
|
| 203 |
+
else: # Complex Lines
|
| 204 |
+
output = model1(input_tensor)
|
| 205 |
|
| 206 |
+
# Convert tensor to low-res PIL image
|
| 207 |
line_drawing_low_res = transforms.ToPILImage()(output.squeeze().cpu().clamp(0, 1))
|
|
|
|
| 208 |
|
| 209 |
+
# Resize the line drawing back to the original image size *before* applying filters
|
| 210 |
+
line_drawing_full_res = line_drawing_low_res.resize(original_size, Image.Resampling.BICUBIC)
|
| 211 |
+
|
| 212 |
+
# Apply the selected filter
|
| 213 |
final_image = apply_filter(line_drawing_full_res, filter_name, original_img)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
+
return final_image
|
|
|
|
| 216 |
|
| 217 |
+
# 🚀 Setup and launch the Gradio interface
|
| 218 |
title = "🖌️ Image to Line Art with Creative Filters"
|
| 219 |
+
description = "Upload an image, choose a line style (Complex or Simple), and select a filter from the dropdown to transform your picture into unique line art."
|
| 220 |
+
|
| 221 |
+
# Generate dropdown choices with emojis
|
| 222 |
+
filter_choices = [f"{emoji} {name}" for name, emoji in FILTERS.items()]
|
| 223 |
+
|
| 224 |
+
# Dynamically generate examples from images in the current directory
|
| 225 |
+
examples = []
|
| 226 |
+
image_dir = '.'
|
| 227 |
+
if os.path.exists(image_dir):
|
| 228 |
+
image_files = [f for f in os.listdir(image_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]
|
| 229 |
+
if image_files:
|
| 230 |
+
# Pick the first image found and create examples with a few interesting filters
|
| 231 |
+
example_image = image_files[0]
|
| 232 |
+
examples.append([example_image, 'Simple Lines', '🗺️ Contour'])
|
| 233 |
+
examples.append([example_image, 'Complex Lines', '🔵⚫ BlueOnBlack'])
|
| 234 |
+
examples.append([example_image, 'Simple Lines', '✖️ Multiply'])
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
iface = gr.Interface(
|
| 238 |
+
fn=predict,
|
| 239 |
+
inputs=[
|
| 240 |
+
gr.Image(type='filepath', label="Upload Image"),
|
| 241 |
+
gr.Radio(['Complex Lines', 'Simple Lines'], label='Line Style', value='Simple Lines'),
|
| 242 |
+
gr.Dropdown(filter_choices, label="Filter", value=filter_choices[0])
|
| 243 |
+
],
|
| 244 |
+
outputs=gr.Image(type="pil", label="Filtered Line Art"),
|
| 245 |
+
title=title,
|
| 246 |
+
description=description,
|
| 247 |
+
examples=examples,
|
| 248 |
+
allow_flagging='never'
|
| 249 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
|
| 251 |
if __name__ == "__main__":
|
| 252 |
+
iface.launch()
|