-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconv_auto_fourier.py
151 lines (118 loc) · 5.25 KB
/
conv_auto_fourier.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
__author__ = 'SherlockLiao'
import torch
import torchvision
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.utils import save_image
import os
from rainy_dataloader_fourier import RainyDataset
import cv2
from model import autoencoder
from skimage.measure import compare_ssim
from utils import *
img_dirs = "./dc_img_fourier"
model_dirs = "./models_fourier"
os.makedirs(img_dirs,exist_ok=True)
os.makedirs(model_dirs,exist_ok=True)
image_size = 64
num_epochs = 10
batch_size = 4
learning_rate = 1e-3
img_transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((image_size,image_size)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
dataset_training = RainyDataset('rainy-image-dataset/training', transform=img_transform)
total_train = len(dataset_training)
dataloader_training = DataLoader(dataset_training, batch_size=batch_size, shuffle=True,num_workers=4)
model = autoencoder().cuda()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,
weight_decay=1e-5)
model.train()
print("Training model, total samples %d"%total_train)
for epoch in range(num_epochs):
epoch_loss = 0
os.makedirs('%s/epoch_%d'%(img_dirs,epoch),exist_ok=True)
ssim = 0
for index,data in enumerate(dataloader_training):
clean_img = data["clean"]
rainy_img = data["rain"]
f_rain = data["fourier_rain"]
clean_img = Variable(clean_img).cuda()
rainy_img = Variable(rainy_img).cuda()
f_rain = Variable(f_rain).float().cuda()
# ===================forward=====================
output = model(f_rain)
loss = criterion(output, clean_img - rainy_img)
epoch_loss += loss.data.item()
# ===================backward====================
optimizer.zero_grad()
loss.backward()
optimizer.step()
# ===================log========================
if (index % 20)== 0:
residual = -output.cpu().data
output = rainy_img + output
# pic = ((rainy_img+1)*0.5 + (output+1)*0.5).clamp(0,1).cpu().data
pic = to_img(output.cpu().data,image_size)
original = to_img(clean_img.cpu().data,image_size)
rainy = to_img(rainy_img.cpu().data,image_size)
frain = to_img(f_rain.cpu().data,image_size)
residual = to_img(-residual.cpu().data,image_size)
#BGR to RGB
permute = [2, 1, 0]
# output=output[:, permute]
pic=pic[:, permute]
original=original[:, permute]
rainy=rainy[:, permute]
save_image(torch.cat((pic,residual,original,rainy,frain)), '%s/epoch_%d/image_%d.jpg'%(img_dirs,epoch,index))
else:
output = rainy_img + output
clean_img = clean_img.cpu().detach().numpy()
output = output.cpu().detach().numpy()
for i in range(batch_size):
ssim += compare_ssim(clean_img[i].transpose(1,2,0),output[i].transpose(1,2,0),data_range = output[i].max() - output[i].min(),multichannel = True)
print('epoch [{}/{}], loss:{:.4f}'
.format(epoch, num_epochs-1, epoch_loss/total_train))
print("SSIM: %f"%(ssim/total_train))
torch.save(model.state_dict(), '%s/conv_autoencoder_%d.pth'%(model_dirs,epoch))
dataset_testing = RainyDataset('rainy-image-dataset/testing', transform=img_transform)
total_test = len(dataset_testing)
dataloader_testing = DataLoader(dataset_testing, batch_size=batch_size, shuffle=True,num_workers=4)
# model.load_state_dict(torch.load("%s/conv_autoencoder_9.pth"%model_dirs))
print("Validating model, total samples %d"%total_test)
model.eval()
test_loss = 0
os.makedirs('%s/testing'%img_dirs,exist_ok=True)
ssim = 0
for index,data in enumerate(dataloader_testing):
clean_img = data["clean"]
rainy_img = data["rain"]
f_rain = data["fourier_rain"]
clean_img = Variable(clean_img).cuda()
rainy_img = Variable(rainy_img).cuda()
f_rain = Variable(f_rain).float().cuda()
# ===================forward=====================
output = model(f_rain)
loss = criterion(output, clean_img - rainy_img)
test_loss += loss.data.item()
# ===================log========================
residual = -output.cpu().data
# print(residual.shape)
output = rainy_img + output
permute = [2,1,0]
pic = to_img(output.cpu().data,image_size)[:,permute]
original = to_img(clean_img.cpu().data,image_size)[:,permute]
rainy = to_img(rainy_img.cpu().data,image_size)[:,permute]
save_image(torch.cat((pic,residual,original,rainy)), '%s/testing/image_%d.jpg'%(img_dirs,index))
output = output.cpu().detach().numpy()
clean_img = clean_img.cpu().detach().numpy()
for i in range(batch_size):
ssim += compare_ssim(clean_img[i].transpose(1,2,0),output[i].transpose(1,2,0),data_range = output[i].max() - output[i].min(),multichannel = True)
print("Test loss",test_loss/total_test)
print("SSIM: %f"%(ssim/total_test))