-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyauto_rain2norain.py
270 lines (228 loc) · 11 KB
/
pyauto_rain2norain.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
#--------------------------------------------------Hi Andy! This code is for autoencoder rain to norain ,I believe you can understand what the code mean ----------------------------
import torch
import random
import cv2
import torch.nn as nn
import torch.utils.data as Data
from torchvision.utils import save_image
import torchvision
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
from torchvision import transforms, utils
from torch.autograd import Variable
# torch.manual_seed(1) # reproducible
def progbar(curr, total, full_progbar, is_done) :
"""
Plot progress bar on terminal
Args :
curr (int) : current progress
total (int) : total progress
full_progbar (int) : length of progress bar
is_done (bool) : is already done
"""
frac = curr/total
filled_progbar = round(frac*full_progbar)
if is_done == True :
print('\r|'+'#'*full_progbar + '| [{:>7.2%}]'.format(1) , end='')
else :
print('\r|'+'#'*filled_progbar + '-'*(full_progbar-filled_progbar) + '| [{:>7.2%}]'.format(frac) , end='')
np.set_printoptions(threshold=np.nan)
# Hyper Parameters
EPOCH = 100
BATCH_SIZE = 4
NUM_SHOW_IMG = 4
LR = 0.005 # learning rate
DOWNLOAD_MNIST = False
STEP_NUM = 24000
#Star to load data
train_data = torchvision.datasets.ImageFolder(
'./project_derain/train_rain/',
transform=transforms.Compose([
#transforms.Resize((256, 256), 3),
transforms.ToTensor()
])
)
train_data_GT = torchvision.datasets.ImageFolder(
'./project_derain/train_norain/',
transform=transforms.Compose([
#transforms.Resize((256, 256), 3),
transforms.ToTensor()
])
)
print('train_data is: ',train_data)
#print('train_data[:BATCH_SIZE] is: ',train_data[:BATCH_SIZE])
#print('train_data[:BATCH_SIZE] size is: ',train_data[:BATCH_SIZE].size())
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=False)
print('train_loader is: ',train_loader) #train_ltoader is: <torch.utils.data.dataloader.DataLoader object at 0x0000028E0D8A3BA8>
print('train_loader type is: ',type(train_loader))
train_loader_GT = Data.DataLoader(dataset=train_data_GT, batch_size=BATCH_SIZE, shuffle=False)
class AutoEncoder(nn.Module):
def __init__(self):
super(AutoEncoder, self).__init__()
self.encoder = nn.Sequential( # input shape (3, 512, 512)
nn.Conv2d(
in_channels=3, # input height
out_channels=64, # n_filters
kernel_size=3, # filter size
stride=2, # filter movement/step
padding=1, # if want same width and length of this image after con2d, padding=(kernel_size-1)/2 if stride=1
), # output shape (16, 512, 512)
nn.LeakyReLU(), # activation
nn.Conv2d(64, 128, 3, 2, 1), # output shape (32, 256, 256)
nn.BatchNorm2d(num_features = 128, affine = True),
nn.LeakyReLU(), # activation
nn.Conv2d(128, 256, 3, 2, 1), # output shape (64, 128, 128)
nn.BatchNorm2d(num_features = 256, affine = True),
nn.LeakyReLU(),
nn.Conv2d(256, 512, 3, 2, 1), # output shape (64, 128, 128)
nn.BatchNorm2d(num_features = 512, affine = True),
nn.LeakyReLU(),
nn.Conv2d(512, 1024, 3, 2, 1), # output shape (64, 128, 128)
nn.BatchNorm2d(num_features = 1024, affine = True),
nn.LeakyReLU(),
)
self.decoder = nn.Sequential(
nn.ConvTranspose2d(
in_channels=1024,
out_channels=512,
kernel_size=4,
stride=2,
padding=1,
),
nn.BatchNorm2d(num_features = 512, affine = True),
nn.LeakyReLU(),
nn.ConvTranspose2d(512,256,4,2,1),
nn.BatchNorm2d(num_features = 256, affine = True),
nn.LeakyReLU(),
nn.ConvTranspose2d(256,128,4,2,1),
nn.BatchNorm2d(num_features = 128, affine = True),
nn.LeakyReLU(),
nn.ConvTranspose2d(128,64,4,2,1),
nn.BatchNorm2d(num_features = 64, affine = True),
nn.LeakyReLU(),
nn.ConvTranspose2d(64,3,4,2,1),
nn.LeakyReLU(),
)
def forward(self, x):
encoder = self.encoder(x)
decoder = self.decoder(encoder)
return encoder, decoder
autoencoder = AutoEncoder().cuda()
optimizer = torch.optim.Adam(autoencoder.parameters(), lr=LR)
loss_func = nn.L1Loss().cuda()
# initialize figure
f, a = plt.subplots(2, NUM_SHOW_IMG, figsize=(5, 2))
plt.ion() # continuously plot
img_ground_list = None
from scipy import misc
'''
# test
img_rain_list = []
img_nonrain_list = []
for i, data in enumerate(train_loader,0):
images, labels = data
for idx in range(BATCH_SIZE) :
if labels[idx] == 0 :
img_nonrain_list.append(images[idx])
else :
img_rain_list.append(images[idx])
print('img_rain_list 0 is: {}'.format(img_nonrain_list[0]))
print('img_rain_list 0 size is: {}'.format(img_nonrain_list[0].shape))
img_nonrain_list[0] = img_nonrain_list[0].transpose(0,1).transpose(1,2) #chahge (3,512,512) to (512,512,3)
img_nonrain_list[0].data.cpu().numpy() #torch to array(not necessary)
print('img_rain_list[0] shape: {}'.format(img_nonrain_list[0].shape))
print('img_rain_list len is: {}'.format(len(img_rain_list)))
print('img_nonrain_list len is: {}'.format(len(img_nonrain_list)))
# misc.imsave('YOHEYNO.jpg', img_rain_list[0]) #save array format image
input()
'''
# original data (first row) for viewing
for i, data in enumerate(train_loader,0):
images, labels = data
img_ground_list = images[:NUM_SHOW_IMG] #0-1 float
# print(A.size()) #torch.Size([5, 3, 512, 512])
break
for i in range(NUM_SHOW_IMG):
a[0][i].imshow(transforms.ToPILImage()(img_ground_list[i]))
a[0][i].set_xticks(())
a[0][i].set_yticks(())
random_index = list(range(12000))
random.shuffle(random_index)
for epoch in range(EPOCH):
progress = 0
for step, (b_img, b_label) in enumerate(train_loader):
(c_img, c_label) = iter(train_loader_GT).next()
# print('step: ',step)
# print('img ',images)
# print('img size is: {}'.format(images.size())) #torch.Size([16, 3, 512, 512])
# print('img 0 size is: {}'.format(images[0].size())) #torch.Size([3, 512, 512])
# print('label',labels) # tensor([ 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0])
# print('label size is: {}'.format(labels.size())) #torch.Size([16])
# b0 = b_img[0].transpose(0,1).transpose(1,2).data.cpu().numpy()
# b1 = b_img[1].transpose(0,1).transpose(1,2).data.cpu().numpy()
# b2 = b_img[2].transpose(0,1).transpose(1,2).data.cpu().numpy()
# b3 = b_img[3].transpose(0,1).transpose(1,2).data.cpu().numpy()
# c0 = c_img[0].transpose(0,1).transpose(1,2).data.cpu().numpy()
# c1 = c_img[1].transpose(0,1).transpose(1,2).data.cpu().numpy()
# c2 = c_img[2].transpose(0,1).transpose(1,2).data.cpu().numpy()
# c3 = c_img[3].transpose(0,1).transpose(1,2)
# misc.imsave('b0.jpg', b0) #save array format image
# misc.imsave('b1.jpg', b1) #save array format image
# misc.imsave('b2.jpg', b2)
# misc.imsave('b3.jpg', b3)
# misc.imsave('c0.jpg', c0)
# misc.imsave('c1.jpg', c1)
# misc.imsave('c2.jpg', c2)
# misc.imsave('c3.jpg', c3)
b_x = b_img.cuda()
b_y = c_img.cuda()
# print('step: ',step)
# print('b_img ',b_img)
# print('b_img size is: {}'.format(b_img.size())) #torch.Size([16, 3, 512, 512])
# print('b_label',b_label) # tensor([ 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0])
# print('b_label size is: {}'.format(b_label.size())) #torch.Size([16])
# input()
# b_x = b_img.cuda()#Variable(x.view(-1, 3*512*512)) # batch x, shape (batch, 512*512)
# b_y = c_img.cuda()
encoded, decoded = autoencoder(b_x)
#if step % STEP_NUM == 0:
#img_to_save = decoded.data
#save_image(img_to_save,'res/%s-%s.jpg'%(epoch,step))
#io.imsave('res/{}.jpg'.format(epoch),img_to_save[0])
loss = loss_func(decoded, b_y) # mean square error
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients
#print('[{}][{}/{}]'.format(epoch, step, STEP_NUM))
if step % STEP_NUM == 0:
print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.cpu().numpy())
progbar(progress, STEP_NUM, 40, (progress == STEP_NUM-1))
progress += 1
if step % 60 == 0:
# plotting decoded image (second row)
_, decoded_data = autoencoder(img_ground_list.cuda())
for i in range(NUM_SHOW_IMG):
'''
final_decoded_data = torch.mul(decoded_data.data[i].detach(), 255.0)
#final_decoded_data = final_decoded_data.type(torch.ByteTensor).cpu().numpy()
#final_decoded_data = transforms.ToPILImage()(final_decoded_data)
final_decoded_data = np.reshape(final_decoded_data.type(torch.ByteTensor).cpu().numpy(), (256, 256, 3))
#final_decoded_datas = final_decoded_datas.type(torch.ByteTensor).cpu().numpy()
final_decoded_data = transforms.ToPILImage(mode = 'RGB')(final_decoded_data)
#final_decoded_data = final_decoded_datas[i]
'''
#To visiual training process , you need to save the result first(in the 'res' folder),and then read the result to visual
img_to_save = decoded_data.data[i]
save_image(img_to_save, 'res/{}-{}-{}.jpg'.format(i, epoch, step))
img_tmp = cv2.imread('res/{}-{}-{}.jpg'.format(i, epoch, step))
img_tmp = cv2.cvtColor(img_tmp, cv2.COLOR_BGR2RGB)
a[1][i].clear()
a[1][i].imshow(img_tmp)
a[1][i].set_xticks(())
a[1][i].set_yticks(())
plt.draw()
plt.pause(0.05)
plt.ioff()
plt.show()