-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconv_auto.py
executable file
·137 lines (105 loc) · 4.61 KB
/
conv_auto.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
__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 import RainyDataset
import cv2
from model import autoencoder
from skimage.measure import compare_ssim
from utils import *
image_dirs = "./dc_img"
model_dirs = "./models"
os.makedirs(image_dirs,exist_ok=True)
os.makedirs(model_dirs,exist_ok=True)
image_size = 64
num_epochs = 10
batch_size = 16
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
ssim = 0
os.makedirs('%s/epoch_%d'%(image_dirs,epoch),exist_ok=True)
for index,data in enumerate(dataloader_training):
clean_img = data["clean"]
rainy_img = data["rain"]
clean_img = Variable(clean_img).cuda()
rainy_img = Variable(rainy_img).cuda()
# ===================forward=====================
output = model(rainy_img)
loss = criterion(output, clean_img)
epoch_loss += loss.data.item()
# ===================backward====================
optimizer.zero_grad()
loss.backward()
optimizer.step()
# ===================log========================
if (index % 20)== 0:
pic = to_img(output.cpu().data,image_size)
# print(pic.shape)
original = to_img(clean_img.cpu().data,image_size)
# print(original.shape)
rainy = to_img(rainy_img.cpu().data,image_size)
#BGR to RGB
permute = [2, 1, 0]
pic=pic[:, permute]
original=original[:, permute]
rainy=rainy[:, permute]
save_image(torch.cat((pic,original,rainy)), './dc_img/epoch_%d/image_%d.png'%(epoch,index))
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:{:.5f}'
.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'%image_dirs,exist_ok=True)
ssim = 0
for index,data in enumerate(dataloader_testing):
clean_img = data["clean"]
rainy_img = data["rain"]
clean_img = Variable(clean_img).cuda()
rainy_img = Variable(rainy_img).cuda()
# ===================forward=====================
output = model(rainy_img)
loss = criterion(output, clean_img)
test_loss += loss.data.item()
# ===================log========================
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,original,rainy)), '%s/testing/image_%d.png'%(image_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))