Om-Alve commited on
Commit
7c7ae15
·
1 Parent(s): 5899cb8

Initial commit

Browse files
Files changed (3) hide show
  1. app.py +97 -0
  2. license.txt +21 -0
  3. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import numpy as np
5
+ import matplotlib.pyplot as plt
6
+ import torchvision.transforms as transforms
7
+ from PIL import Image
8
+ from tqdm import tqdm
9
+ import gradio as gr
10
+
11
+ model = torch.hub.load('pytorch/vision:v0.10.0', 'vgg19', pretrained=True)
12
+
13
+ feature_layers = [0,5,10,19,28]
14
+
15
+ class StyleTransfer(nn.Module):
16
+ def __init__(self):
17
+ super().__init__()
18
+ self.model = model
19
+ self.feature_layers = feature_layers
20
+ self.avg_pool = nn.AvgPool2d(kernel_size=2,stride=2,padding=0,ceil_mode=False)
21
+ def forward(self,x):
22
+ style_features = []
23
+ for i,layer in enumerate(self.model.features[:29]):
24
+ if isinstance(layer,nn.MaxPool2d):
25
+ x = self.avg_pool(x)
26
+ continue
27
+ x = layer(x)
28
+ if i in self.feature_layers:
29
+ style_features.append(x)
30
+ if i == 23:
31
+ content_features = x
32
+
33
+ return style_features,content_features
34
+
35
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
36
+
37
+ def image_merger(content, style,beta=10,device=device):
38
+ size = 400
39
+ alpha = 1
40
+ beta *= 1000
41
+ content = Image.fromarray(content)
42
+ style = Image.fromarray(style)
43
+ t = transforms.Compose(
44
+ [
45
+ transforms.Resize((size,size)),
46
+ transforms.ToTensor(),
47
+ ]
48
+ )
49
+ style = t(style).unsqueeze(0).to(device)
50
+ content = t(content).unsqueeze(0).to(device)
51
+ generated = content.clone().to(device).requires_grad_(True)
52
+ generator = StyleTransfer().to(device).eval()
53
+ opt = torch.optim.Adam([generated],lr=0.06)
54
+ scheduler = torch.optim.lr_scheduler.StepLR(opt, step_size=5, gamma=0.9) # Learning rate scheduler
55
+ num_epochs = 30 if device == "cpu" else 100
56
+ style_features,_ = generator(style)
57
+ _,content_features = generator(content)
58
+ loop = tqdm(range(num_epochs),leave=False)
59
+ for i in loop:
60
+ content_loss = 0
61
+ style_loss = 0
62
+ generated_style_features,generated_content_features = generator(generated)
63
+ content_loss = 0.5 * torch.mean((content_features - generated_content_features) ** 2)
64
+ for style_feature,generated_style_feature in zip(style_features,generated_style_features):
65
+ b,c,h,w = style_feature.shape
66
+ s1 = style_feature.view(c,h*w) @ style_feature.view(c,h*w).T
67
+ s2 = generated_style_feature.view(c,h*w) @ generated_style_feature.view(c,h*w).T
68
+
69
+ layer_style_loss = torch.mean((s2 - s1)**2)/(4 *(c) * (h*w))
70
+ style_loss += layer_style_loss
71
+ total_loss = alpha * content_loss + beta * style_loss
72
+ loop.set_postfix(loss=total_loss.item())
73
+ opt.zero_grad()
74
+ total_loss.backward(retain_graph=True)
75
+ opt.step()
76
+ scheduler.step()
77
+ if total_loss < 200 and device=='cpu':
78
+ break
79
+ print(total_loss.item())
80
+ img = np.array(generated.cpu().detach().squeeze(0).permute(1,2,0))
81
+ img = np.clip(img,0,1) * 255
82
+ img = Image.fromarray(img.astype(np.uint8))
83
+ return img
84
+
85
+ iface = gr.Interface(
86
+ fn=image_merger,
87
+ inputs=[
88
+ gr.Image(label="Input Image"),
89
+ gr.Image(label="Style Image"),
90
+ gr.Slider(label="Style strength", minimum=10, maximum=100, step=10),
91
+ ],
92
+ outputs=gr.Image(label="Generated Image"),
93
+ title="Neural Style Transfer",
94
+ description="Upload your desired input image and style image. Adjust the 'Style strength' slider to control the intensity of the style transfer. The generated image will showcase your input content with the stylistic elements of the chosen style image. Generation can take upto two minutes",
95
+ )
96
+
97
+ iface.launch()
license.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Om Alve
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ pytorch
2
+ gradio
3
+ PIL
4
+ tqdm