-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathneuralart.py
291 lines (199 loc) · 9.18 KB
/
neuralart.py
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/bin/python
### imports (should be covered by requirements.txt)
from torch.autograd import Variable
from torchvision import transforms
from torch import optim
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torch
import time
import sys
import os
from collections import OrderedDict
import matplotlib.pyplot as plt
from PIL import Image
### path definitions
model_path = 'weights/vgg_conv_weights.pth'
image_path = '' # by default use neural-art as relative dir
### userland testing for multiple instances, a big nono currently
n_instances = os.popen('ps aux | grep "python neuralart.py" | wc -l').read() # TODO: add windows commands for platform compatibility :p for the 3 people who need this warning
if int(n_instances) > 3: print("Woah, running 2 or more instances of neural-art at the same time?\nThis is an experimental feature as of now... try it later :3")
### check if there are any weights to use, if not, download the default provided ones
if int(os.popen('ls -l weights | wc -l').read()) == 1: os.system(f'curl https://files.catbox.moe/wcao20.pth --output {model_path}') # TODO: win commands here as well
### Defining neural architecture
### VGG was trained on IMAGENET
### although old at this point
### it still achieves good results
class VGG(nn.Module):
def __init__(self, pool='max'):
super(VGG, self).__init__()
self.conv1_1 = nn.Conv2d(3, 64, kernel_size = 3, padding = 1)
self.conv1_2 = nn.Conv2d(64, 64, kernel_size = 3, padding = 1)
self.conv2_1 = nn.Conv2d(64, 128, kernel_size = 3, padding = 1)
self.conv2_2 = nn.Conv2d(128, 128, kernel_size = 3, padding = 1)
self.conv3_1 = nn.Conv2d(128, 256, kernel_size = 3, padding = 1)
self.conv3_2 = nn.Conv2d(256, 256, kernel_size = 3, padding = 1)
self.conv3_3 = nn.Conv2d(256, 256, kernel_size = 3, padding = 1)
self.conv3_4 = nn.Conv2d(256, 256, kernel_size = 3, padding = 1)
self.conv4_1 = nn.Conv2d(256, 512, kernel_size = 3, padding = 1)
self.conv4_2 = nn.Conv2d(512, 512, kernel_size = 3, padding = 1)
self.conv4_3 = nn.Conv2d(512, 512, kernel_size = 3, padding = 1)
self.conv4_4 = nn.Conv2d(512, 512, kernel_size = 3, padding = 1)
self.conv5_1 = nn.Conv2d(512, 512, kernel_size = 3, padding = 1)
self.conv5_2 = nn.Conv2d(512, 512, kernel_size = 3, padding = 1)
self.conv5_3 = nn.Conv2d(512, 512, kernel_size = 3, padding = 1)
self.conv5_4 = nn.Conv2d(512, 512, kernel_size = 3, padding = 1)
# POOLING OPTIONS
if pool == 'max':
self.pool1 = nn.MaxPool2d(kernel_size = 2, stride = 2)
self.pool2 = nn.MaxPool2d(kernel_size = 2, stride = 2)
self.pool3 = nn.MaxPool2d(kernel_size = 2, stride = 2)
self.pool4 = nn.MaxPool2d(kernel_size = 2, stride = 2)
self.pool5 = nn.MaxPool2d(kernel_size = 2, stride = 2)
elif pool == 'avg':
self.pool1 = nn.AvgPool2d(kernel_size = 2, stride = 2)
self.pool2 = nn.AvgPool2d(kernel_size = 2, stride = 2)
self.pool3 = nn.AvgPool2d(kernel_size = 2, stride = 2)
self.pool4 = nn.AvgPool2d(kernel_size = 2, stride = 2)
self.pool5 = nn.AvgPool2d(kernel_size = 2, stride = 2)
def forward(self, x, out_keys):
out = {}
out['r11'] = F.relu(self.conv1_1(x))
out['r12'] = F.relu(self.conv1_2(out['r11']))
out['p1'] = self.pool1(out['r12'])
out['r21'] = F.relu(self.conv2_1(out['p1']))
out['r22'] = F.relu(self.conv2_2(out['r21']))
out['p2'] = self.pool2(out['r22'])
out['r31'] = F.relu(self.conv3_1(out['p2']))
out['r32'] = F.relu(self.conv3_2(out['r31']))
out['r33'] = F.relu(self.conv3_3(out['r32']))
out['r34'] = F.relu(self.conv3_4(out['r33']))
out['p3'] = self.pool3(out['r34'])
out['r41'] = F.relu(self.conv4_1(out['p3']))
out['r42'] = F.relu(self.conv4_2(out['r41']))
out['r43'] = F.relu(self.conv4_3(out['r42']))
out['r44'] = F.relu(self.conv4_4(out['r43']))
out['p4'] = self.pool4(out['r44'])
out['r51'] = F.relu(self.conv5_1(out['p4']))
out['r52'] = F.relu(self.conv5_2(out['r51']))
out['r53'] = F.relu(self.conv5_3(out['r52']))
out['r54'] = F.relu(self.conv5_4(out['r53']))
out['p5'] = self.pool5(out['r54'])
# RETURN DESIRED ACTIVATIONS
return [out[key] for key in out_keys]
### COMPUTING GRAM MATRIX AND GRAM MATRIX LOSS
# GRAM MATRICES ARE USED TO MEASURE STYLE LOSS
class GramMatrix(nn.Module):
def forward(self, input):
b, c, w, h = input.size()
F = input.view(b, c, h * w)
# COMPUTES GRAM MATRIX BY MULTIPLYING INPUT BY TRANPOSE OF ITSELF
G = torch.bmm(F, F.transpose(1, 2))
G.div_(h*w)
return G
class GramMSELoss(nn.Module):
def forward(self, input, target):
out = nn.MSELoss()(GramMatrix()(input), target)
return out
### IMAGE PROCESSING
# "based" on how much vram you have,
# you can either set this to 1080
# as in 1080p or do what i did:
# set the resolution to 720p, and cry.
img_size = 720
# PRE-PROCESSING
prep = transforms.Compose([transforms.Resize(img_size),
transforms.ToTensor(),
transforms.Lambda(lambda x: x[torch.LongTensor([2, 1, 0])]), # CONVERT TO BGR FOR VGG
transforms.Normalize(mean = [0.40760392, 0.45795686, 0.48501961], std = [1, 1, 1]), # SUBTRACT IMAGENET MEAN
transforms.Lambda(lambda x: x.mul_(255)) # VGG WAS TRAINED WITH PIXEL VALUES 0-255
])
# POST-PROCESSING A
postpa = transforms.Compose([transforms.Lambda(lambda x: x.mul_(1./255)), # REVERT EVERYTHING DONE IN THE PRE-PROCESSING STEP
transforms.Normalize(mean = [-0.40760392, -0.45795686, -0.48501961], std = [1, 1, 1]),
transforms.Lambda(lambda x: x[torch.LongTensor([2,1,0])])
])
# POST-PROCESSING B
postpb = transforms.Compose([transforms.ToPILImage()])
# POST PROCESSING FUNCTION INCORPORATES A AND B, AND CLIPS PIXEL VALUES WHICH ARE OUT OF RANGE
def postp(tensor):
t = postpa(tensor)
t[t>1] = 1 # everything above 1 receives value 1
t[t<0] = 0 # analogous for everything lower than 0
img = postpb(t)
return img
### PREPARING NETWORK ARCHITECTURE
vgg = VGG()
vgg.load_state_dict(torch.load(model_path))
for param in vgg.parameters():
param.requires_grad = False
if torch.cuda.is_available():
vgg.cuda()
### LOADING AND PREPARING IMAGES
img_paths = [image_path, image_path]
# IMAGE LOADING ORDER: [STYLE, CONTENT]
img_names = [sys.argv[1], sys.argv[2]]
imgs = [Image.open(img_paths[i] + name) for i, name in enumerate(img_names)]
imgs_torch = [prep(img) for img in imgs]
# HANDLE CUDA
if torch.cuda.is_available():
imgs_torch = [Variable(img.unsqueeze(0)).cuda() for img in imgs_torch]
else:
imgs_torch = [Variable(img.unsqueeze(0)) for img in imgs_torch]
style_img, content_img = imgs_torch
# SET UP IMAGE TO BE OPTIMIZED
# CAN BE INITIALIZED RANDOMLY
# OR AS A CLONE OF CONTENT IMAGE
opt_img = Variable(content_img.clone(), requires_grad = True)
print("Content size:", content_img.size(), sys.argv[2], "in", sys.argv[1])
print("Target size:", opt_img.size(), end="\n\n")
### SETUP FOR TRAINING
# LAYERS FOR STYLE AND CONTENT LOSS
style_layers = ['r11', 'r12', 'r31', 'r41', 'r51']
content_layers = ['r42']
loss_layers = style_layers + content_layers
# CREATING LOSS FUNCTION
loss_fns = [GramMSELoss()] * len(style_layers) + [nn.MSELoss()] * len(content_layers)
if torch.cuda.is_available():
loss_fns = [loss_fn.cuda() for loss_fn in loss_fns]
# SETUP WEIGHTS FOR LOSS LAYERS
style_weights = [1e3/n**2 for n in [64, 128, 256, 512, 512]]
content_weights = [1e0]
weights = style_weights + content_weights
# CREATE OPTIMIZATION TARGETS
style_targets = [GramMatrix()(A).detach() for A in vgg(style_img, style_layers)]
content_targets = [A.detach() for A in vgg(content_img, content_layers)]
targets = style_targets + content_targets
### TRAINING LOOP
import numpy as np
from tqdm import tqdm
vis_factor = 10 # every 10 iterations, a frame snapshot is saved, we use this coeficient to scale
max_iter = 600 * vis_factor
show_iter = 1 * vis_factor
optimizer = optim.LBFGS([opt_img])
n_iter = [0]
image_array = []
with tqdm(total=max_iter, miniters=0, smoothing=0) as pbar:
while n_iter[0] <= max_iter - 9: # weird behavior here
def closure():
optimizer.zero_grad()
# FORWARD
out = vgg(opt_img, loss_layers)
# LOSS
layer_losses = [weights[a] * loss_fns[a](A, targets[a]) for a,A in enumerate(out)]
loss = sum(layer_losses)
# BACKWARDS
loss.backward()
# TRACK PROGRESS
if n_iter[0] % show_iter == 0:
out_img = postp(opt_img.data[0].cpu().squeeze())
image_array.append(np.array(out_img))
pbar.update(show_iter)
n_iter[0] += 1
return loss
optimizer.step(closure)
# SAVE ARRAY TO FILE
image_array = np.array(image_array)
np.save('images.npy', image_array)
print("")