Spaces:
Build error
Build error
File size: 5,646 Bytes
25ed4e6 62e768f a7a571c fb0fae6 34f62d8 3d76444 2f5ca9b 3d76444 62e768f 3d76444 62e768f 3d76444 3da0d10 3d76444 3da0d10 3d76444 904d644 3d76444 62e768f 6da67e3 3d76444 25ed4e6 3d76444 be24459 3d76444 34f62d8 3d76444 25ed4e6 3d76444 3da0d10 3d76444 34f62d8 3d76444 25ed4e6 34f62d8 6da67e3 34f62d8 6da67e3 25ed4e6 3d76444 62e768f 3d76444 62e768f 25ed4e6 62e768f 6da67e3 62e768f 6da67e3 3d76444 a4555cf 62e768f a7a571c | 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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | import numpy as np
import torch
import torch.nn as nn
import gradio as gr
import cv2
import os
from PIL import Image
from PIL import ImageEnhance
import torchvision.transforms as transforms
# π§ Neural network layers
norm_layer = nn.InstanceNorm2d
# π§± Building block for the generator
class ResidualBlock(nn.Module):
def __init__(self, in_features):
super(ResidualBlock, self).__init__()
conv_block = [ nn.ReflectionPad2d(1),
nn.Conv2d(in_features, in_features, 3),
norm_layer(in_features),
nn.ReLU(inplace=True),
nn.ReflectionPad2d(1),
nn.Conv2d(in_features, in_features, 3),
norm_layer(in_features)
]
self.conv_block = nn.Sequential(*conv_block)
def forward(self, x):
return x + self.conv_block(x)
# π¨ Generator model for creating line drawings
class Generator(nn.Module):
def __init__(self, input_nc, output_nc, n_residual_blocks=9, sigmoid=True):
super(Generator, self).__init__()
# π Initial convolution block
model0 = [ nn.ReflectionPad2d(3),
nn.Conv2d(input_nc, 64, 7),
norm_layer(64),
nn.ReLU(inplace=True) ]
self.model0 = nn.Sequential(*model0)
# π½ Downsampling
model1 = []
in_features = 64
out_features = in_features*2
for _ in range(2):
model1 += [ nn.Conv2d(in_features, out_features, 3, stride=2, padding=1),
norm_layer(out_features),
nn.ReLU(inplace=True) ]
in_features = out_features
out_features = in_features*2
self.model1 = nn.Sequential(*model1)
# π Residual blocks
model2 = []
for _ in range(n_residual_blocks):
model2 += [ResidualBlock(in_features)]
self.model2 = nn.Sequential(*model2)
# πΌ Upsampling
model3 = []
out_features = in_features//2
for _ in range(2):
model3 += [ nn.ConvTranspose2d(in_features, out_features, 3, stride=2, padding=1, output_padding=1),
norm_layer(out_features),
nn.ReLU(inplace=True) ]
in_features = out_features
out_features = in_features//2
self.model3 = nn.Sequential(*model3)
# π Output layer
model4 = [ nn.ReflectionPad2d(3),
nn.Conv2d(64, output_nc, 7)]
if sigmoid:
model4 += [nn.Sigmoid()]
self.model4 = nn.Sequential(*model4)
def forward(self, x, cond=None):
out = self.model0(x)
out = self.model1(out)
out = self.model2(out)
out = self.model3(out)
out = self.model4(out)
return out
# π§ Load the models
model1 = Generator(3, 1, 3) # Initialize the model architecture
model1.load_state_dict(torch.load('model.pth', map_location=torch.device('cpu')))
model1.eval() # Set the model to evaluation mode
model2 = Generator(3, 1, 3) # Initialize the model architecture
model2.load_state_dict(torch.load('model2.pth', map_location=torch.device('cpu')))
model2.eval() # Set the model to evaluation mode
# πΌοΈ Function to process the image and create line drawing
def predict(input_img, ver):
# Open the image and get its original size
original_img = Image.open(input_img)
original_size = original_img.size
# Define the transformation pipeline
transform = transforms.Compose([
transforms.Resize(512, Image.BICUBIC),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # Normalize to [-1, 1]
])
# Apply the transformation
input_tensor = transform(original_img)
input_tensor = input_tensor.unsqueeze(0)
# Process the image through the model
with torch.no_grad():
if ver == 'Simple Lines':
output = model2(input_tensor)
else:
output = model1(input_tensor)
# Convert the output tensor to an image
output_img = transforms.ToPILImage()(output.squeeze().cpu().clamp(0, 1)) # Clamp the output to [0, 1]
# Resize the output image back to the original size
output_img = output_img.resize(original_size, Image.BICUBIC)
# Enhance the contrast to make the black areas deeper
enhancer = ImageEnhance.Contrast(output_img)
output_img = enhancer.enhance(2.0) # Increase contrast (values > 1 increase contrast, < 1 reduce contrast)
# Optionally enhance the brightness slightly if the image is still too dark
brightness_enhancer = ImageEnhance.Brightness(output_img)
output_img = brightness_enhancer.enhance(1.0) # Keep brightness the same, adjust if needed
return output_img
# π Title for the Gradio interface
title="ποΈ Image to Simple and Complex Artistic Drawings"
# πΌοΈ Dynamically generate examples from images in the directory
examples = []
image_dir = '.' # Assuming images are in the current directory
for file in os.listdir(image_dir):
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
examples.append([file, 'Simple Lines'])
examples.append([file, 'Complex Lines'])
# π Create and launch the Gradio interface
iface = gr.Interface(
fn=predict,
inputs=[
gr.Image(type='filepath'),
gr.Radio(['Complex Lines', 'Simple Lines'], label='version', value='Simple Lines')
],
outputs=gr.Image(type="pil"),
title=title,
examples=examples
)
iface.launch()
|