-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
238 lines (197 loc) · 7.71 KB
/
main.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
import argparse
from dataLoadess import Imgdataset
from torch.utils.data import DataLoader
from models import ADMM_net_S4, ADMM_net_S12
from utils import generate_masks, time2file_name, A, At, gen_log
import torch.optim as optim
import torch.nn as nn
import torch
import scipy.io as scio
import time
import datetime
import os
import numpy as np
from torch.autograd import Variable
from mmcv import Config
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
if not torch.cuda.is_available():
raise Exception('NO GPU!')
data_path = "/data/jiamianw/ICCV2021/DAVIS_data/training_data" # "./generated_data" #
test_path1 = "/data/jiamianw/BIRNAT-master/from_yangliu" # "./from_yangliu" #
def parse_args():
parser = argparse.ArgumentParser(description="Train a generator")
parser.add_argument('config', help='train config file')
args = parser.parse_args()
return args
last_train = 0
model_save_filename = ''
max_iter = 200
batch_size = 4
learning_rate = 0.0005
stage_num = 4
mode = 'train' # train or test
n_resblocks = 16
n_feats = 24
lr_scale = 0.8
lr_epoch = 10
mask, mask_s = generate_masks(data_path)
dataset = Imgdataset(data_path)
train_data_loader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True)
#first_frame_net = cnn1().cuda()
args = parse_args() #parse parameter(config file path)
cfg = Config.fromfile(args.config)
if stage_num == 4:
network = ADMM_net_S4(n_resblocks = n_resblocks, n_feats = n_feats, cfg=cfg).cuda()
elif stage_num == 12:
network = ADMM_net_S12(n_resblocks=n_resblocks, n_feats=n_feats, cfg=cfg).cuda()
if last_train != 0:
network = torch.load(
'./model/' + model_save_filename + "/S{}_model_epoch_{}.pth".format(stage_num,last_train))
criterion = nn.MSELoss()
criterion.cuda()
n_parameters = sum(p.numel() for p in network.parameters() if p.requires_grad)
print(f'Trainable parameters: {n_parameters}')
def test(test_path, epoch, result_path, psnr_epoch):
test_list = os.listdir(test_path)
psnr_sample = torch.zeros(len(test_list))
pred = []
for i in range(len(test_list)):
pic = scio.loadmat(test_path + '/' + test_list[i])
if "orig" in pic:
pic = pic['orig']
sign = 1
elif "patch_save" in pic:
pic = pic['patch_save']
sign = 0
elif "p1" in pic:
pic = pic['p1']
sign = 0
elif "p2" in pic:
pic = pic['p2']
sign = 0
elif "p3" in pic:
pic = pic['p3']
sign = 0
pic = pic / 255
pic_gt = np.zeros([pic.shape[2] // 8, 8, 256, 256])
for jj in range(pic.shape[2]):
if jj % 8 == 0:
meas_t = np.zeros([256, 256])
n = 0
pic_t = pic[:, :, jj]
mask_t = mask[n, :, :]
mask_t = mask_t.cpu()
pic_gt[jj // 8, n, :, :] = pic_t
n += 1
meas_t = meas_t + np.multiply(mask_t.numpy(), pic_t)
if jj == 7:
meas_t = np.expand_dims(meas_t, 0)
meas = meas_t
elif (jj + 1) % 8 == 0 and jj != 7:
meas_t = np.expand_dims(meas_t, 0)
meas = np.concatenate((meas, meas_t), axis=0)
meas = torch.from_numpy(meas)
pic_gt = torch.from_numpy(pic_gt)
meas = meas.cuda()
pic_gt = pic_gt.cuda()
meas = meas.float()
pic_gt = pic_gt.float()
batch_size1 = pic_gt.shape[0]
y = meas # [batch,256 256]
Phi = mask.expand([batch_size1, 8, 256, 256])
Phi_s = mask_s.expand([batch_size1, 256, 256])
with torch.no_grad():
out_pic_list = network(y, Phi, Phi_s)
out_pic = out_pic_list[-1]
psnr_1 = 0
for ii in range(meas.shape[0] * 8):
out_pic_p = out_pic[ii // 8, ii % 8, :, :]
gt_t = pic_gt[ii // 8, ii % 8, :, :]
rmse = torch.sqrt(criterion(out_pic_p, gt_t))
rmse = rmse.data
psnr_1 += 10 * torch.log10(1 / criterion(out_pic_p, gt_t))
psnr_1 = psnr_1 / (meas.shape[0] * 8)
psnr_sample[i] = psnr_1
pred.append(out_pic.cpu().numpy())
psnr_epoch.append(psnr_sample)
return pred, psnr_epoch
def train(epoch, learning_rate, logger):
epoch_loss = 0
begin = time.time()
optimizer = optim.Adam(network.parameters(), lr=learning_rate)
if __name__ == '__main__':
for iteration, batch in enumerate(train_data_loader):
gt, meas = Variable(batch[0]), Variable(batch[1])
gt = gt.cuda() # [batch,8,256,256]
gt = gt.float()
meas = meas.cuda() # [batch,256 256]
meas = meas.float()
batch_size1 = gt.shape[0]
y = meas # [batch,256 256]
Phi = mask.expand([batch_size1, 8, 256, 256])
Phi_s = mask_s.expand([batch_size1, 256, 256])
optimizer.zero_grad()
#time_start=time.time()
model_out = network(y, Phi, Phi_s)
#time_end=time.time()
#print('time cost',time_end-time_start,'s')
Loss = torch.sqrt(criterion(model_out[-1], gt)) + 0.5*torch.sqrt(criterion(model_out[-2], gt)) + 0.5*torch.sqrt(criterion(model_out[-3], gt))
epoch_loss += Loss.data
Loss.backward()
optimizer.step()
end = time.time()
logger.info("===> Epoch {} Complete: Avg. Loss: {:.8f}, time: {:.2f}".format(epoch, epoch_loss / len(train_data_loader), end - begin))
def checkpoint(epoch, model_path):
model_out_path = './' + model_path + '/S{}'.format(stage_num) + "_model_epoch_{}.pth".format(epoch)
torch.save(network, model_out_path)
print("Checkpoint saved to {}".format(model_out_path))
def main(learning_rate):
date_time = str(datetime.datetime.now())
date_time = time2file_name(date_time)
result_path = 'recon' + '/' + date_time
model_path = 'model' + '/' + date_time
if not os.path.exists(result_path):
os.makedirs(result_path)
if not os.path.exists(model_path):
os.makedirs(model_path)
psnr_epoch = []
psnr_max = 0
logger = gen_log(model_path)
logger.info('''
model_path = {:s}
data_path = {:s}
test_path1 = {:s}
last_train = {:d}
max_iter = {:d}
batch_size = {:d}
learning_rate = {:.10f}
stage_num = {:d}
n_resblocks = {:d}
n_feats = {:d}
lr_scale = {:.4f}
lr_epoch = {:d}
\n'''.format(model_path, data_path, test_path1,
last_train, max_iter, batch_size,
learning_rate, stage_num, n_resblocks,
n_feats, lr_scale, lr_epoch))
for epoch in range(last_train + 1, last_train + max_iter + 1):
print('----------Train: epoch%d----------'%epoch)
start_trn = time.time()
train(epoch, learning_rate, logger)
end_trn = time.time()
print('----------Train finished, time=%f, Test: epoch%d----------'%((end_trn-start_trn)/60., epoch))
pred, psnr_epoch = test(test_path1, epoch, result_path, psnr_epoch)
psnr_mean = torch.mean(psnr_epoch[-1])
# print("Test result: {:.4f}".format(psnr_mean))
logger.info("epoch {:d}. Test result: {:.4f}".format(epoch, psnr_mean))
if psnr_mean > psnr_max:
psnr_max = psnr_mean
if psnr_mean > 25:
name = result_path + '/S{}'.format(stage_num) + '_pred_' + '{}_{:.4f}'.format(epoch, psnr_mean) + '.mat'
scio.savemat(name, {'pred': pred})
checkpoint(epoch, model_path)
if (epoch % lr_epoch == 0) and (epoch < 200):
learning_rate = learning_rate * lr_scale
print(learning_rate)
if __name__ == '__main__':
main(learning_rate)