-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
executable file
·183 lines (154 loc) · 5.98 KB
/
utils.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
import os
import math
import torch
import logging
import numpy as np
import scipy.io as sio
from ssim_torch import ssim
patch_size = 256
def generate_masks(mask_path, batch_size):
mask = sio.loadmat(mask_path + '/mask.mat')
mask = mask['mask']
mask3d = np.tile(mask[:,:,np.newaxis],(1,1,28))
mask3d = np.transpose(mask3d, [2, 0, 1])
mask3d = torch.from_numpy(mask3d)
[nC, H, W] = mask3d.shape
mask3d_batch = mask3d.expand([batch_size, nC, H, W]).cuda().float()
return mask3d_batch
def mask_binarize(mask3d_batch):
biny_mask = mask3d_batch[:, 0, :, :]
biny_mask[biny_mask > 0.5] = 1.
biny_mask[biny_mask <= 0.5] = 0.
biny_mask = biny_mask.type(torch.LongTensor).cuda()
return biny_mask
def LoadTraining(path):
imgs = []
scene_list = os.listdir(path)
scene_list.sort()
print('training sences:', len(scene_list))
max_ = 0
for i in range(len(scene_list)):
scene_path = path + scene_list[i]
if 'mat' not in scene_path:
continue
img_dict = sio.loadmat(scene_path)
if "img_expand" in img_dict:
img = img_dict['img_expand']/65536.
elif "img" in img_dict:
img = img_dict['img']/65536.
img = img.astype(np.float32)
imgs.append(img)
print('Sence {} is loaded. {}'.format(i, scene_list[i]))
return imgs
def LoadTest(path_test):
scene_list = os.listdir(path_test)
scene_list.sort()
test_data = np.zeros((len(scene_list), 256, 256, 28))
for i in range(len(scene_list)):
scene_path = path_test + scene_list[i]
img = sio.loadmat(scene_path)['img']
#img = img/img.max()
test_data[i,:,:,:] = img
print(i, img.shape, img.max(), img.min())
test_data = torch.from_numpy(np.transpose(test_data, (0, 3, 1, 2)))
return test_data
def LoadTest_real(path_test):
scene_list = os.listdir(path_test)
scene_list.sort()
test_data = np.zeros((len(scene_list), 660, 714, 1))
for i in range(len(scene_list)):
scene_path = path_test + '/' + scene_list[i]
# img = sio.loadmat(scene_path)['img']
img_dict = np.load(scene_path, allow_pickle=True).item()
img = img_dict['meas_real']
#img = img/img.max()
test_data[i,:,:,:] = img[:,:,np.newaxis]
print(i, img.shape, img.max(), img.min())
test_data = torch.from_numpy(np.transpose(test_data, (0, 3, 1, 2)))
return test_data
def psnr(img1, img2):
psnr_list = []
for i in range(img1.shape[0]):
total_psnr = 0
#PIXEL_MAX = img2.max()
PIXEL_MAX = img2[i,:,:,:].max()
for ch in range(28):
mse = np.mean((img1[i,:,:,ch] - img2[i,:,:,ch])**2)
total_psnr += 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
psnr_list.append(total_psnr/img1.shape[3])
return psnr_list
def torch_psnr(img, ref): #input [28,patch_size,patch_size]
nC = img.shape[0]
pixel_max = torch.max(ref)
psnr = 0
for i in range(nC):
mse = torch.mean((img[i,:,:] - ref[i,:,:]) ** 2)
psnr += 20 * torch.log10(pixel_max / torch.sqrt(mse))
return psnr/nC
def torch_ssim(img, ref): #input [28,patch_size,patch_size]
return ssim(torch.unsqueeze(img,0), torch.unsqueeze(ref,0))
def time2file_name(time):
year = time[0:4]
month = time[5:7]
day = time[8:10]
hour = time[11:13]
minute = time[14:16]
second = time[17:19]
time_filename = year + '_' + month + '_' + day + '_' + hour + '_' + minute + '_' + second
return time_filename
def shuffle_crop(train_data, batch_size):
index = np.random.choice(np.arange(len(train_data)), batch_size)
processed_data = np.zeros((batch_size, patch_size, patch_size, 28), dtype=np.float32)
for i in range(batch_size):
h, w, _ = train_data[index[i]].shape
x_index = np.random.randint(0, h - patch_size)
y_index = np.random.randint(0, w - patch_size)
processed_data[i, :, :, :] = train_data[index[i]][x_index:x_index + patch_size, y_index:y_index + patch_size, :] # change
gt_batch = torch.from_numpy(np.transpose(processed_data, (0, 3, 1, 2)))
return gt_batch
# return PhiTy
def gen_meas_torch(data_batch, mask3d_batch, is_training=True):
nC = data_batch.shape[1]
if is_training is False:
[batch_size, nC, H, W] = data_batch.shape
mask3d_batch = (mask3d_batch[0,:,:,:]).expand([batch_size, nC, H, W]).cuda().float()
temp = shift(mask3d_batch*data_batch, 2)
meas = torch.sum(temp, 1)/nC*2
y_temp = shift_back(meas)
PhiTy = torch.mul(y_temp, mask3d_batch)
return PhiTy
def gen_meas_torch_test(data_batch, mask3d_batch):
[batch_size, nC, H, W] = data_batch.shape
mask3d_batch = (mask3d_batch[0,:,:,:]).expand([batch_size, nC, H, W]).cuda().float()
y_temp = shift_back(data_batch)
print('>>>y_temp.shape', y_temp.shape) #
PhiTy = torch.mul(y_temp, mask3d_batch)
# print('>>>PhiTy.shape',PhiTy.shape) # [4, 28, 256, 256]
return PhiTy
def shift(inputs, step=2):
[bs, nC, row, col] = inputs.shape
output = torch.zeros(bs, nC, row, col+(nC-1)*step).cuda().float()
for i in range(nC):
output[:,i,:,step*i:step*i+col] = inputs[:,i,:,:]
return output
def shift_back(inputs,step=2): # input [bs,patch_size,310] output [bs, 28, patch_size, patch_size]
[bs, row, col] = inputs.shape
nC = 28
output = torch.zeros(bs, nC, row, col-(nC-1)*step).cuda().float()
for i in range(nC):
output[:,i,:,:] = inputs[:,:,step*i:step*i+col-(nC-1)*step]
return output
def gen_log(model_path):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(levelname)s: %(message)s")
log_file = model_path + '/log.txt'
fh = logging.FileHandler(log_file, mode='a')
fh.setLevel(logging.INFO)
fh.setFormatter(formatter)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)
return logger