-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_sample.py
191 lines (162 loc) · 6.95 KB
/
test_sample.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
import argparse
import cv2
import importlib
import numpy as np
import os
import sys
import torch
from utils.common import scandir, tensor2img, calculate_psnr_ssim
from utils.model_opr import load_model, load_model_filter_list
def read_image_to_tensor(ipath):
img = cv2.imread(ipath, cv2.IMREAD_COLOR)
img = np.transpose(img[:, :, ::-1], (2, 0, 1)).astype(np.float32) / 255.0
img = torch.from_numpy(img).float().unsqueeze(0)
return img
def lcm(ab):
a, b = ab[0], ab[1]
for i in range(min(a, b), 0, -1):
if a % i == 0 and b % i == 0:
return a * b // i
if __name__ == '__main__':
print('---------- Start ----------')
### load arguments
parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str, required=True)
parser.add_argument('--model', type=str, required=True)
parser.add_argument('--input', type=str, default=None)
parser.add_argument('--output', type=str, default=None)
parser.add_argument('--gt', type=str, default=None)
parser.add_argument('--noise_level', type=int, default=None)
parser.add_argument('--sf', action='store_true')
args = parser.parse_args()
if not args.noise_level:
assert args.input is not None, 'Please assign the input value!'
print('[Input Path]', args.input)
else:
assert args.gt is not None, 'Please assign the gt value for denoising!'
print('[GT Path]', args.gt)
np.random.seed(seed=0)
if args.output:
os.makedirs(args.output, exist_ok=True)
### check config
config_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'configs')
config_files = [
os.path.splitext(os.path.basename(v))[0] for v in scandir(config_root)
if v.endswith('.py')
]
config_file = os.path.basename(args.config).split('.')[0]
assert config_file in config_files, 'Illegal config!'
module_reg = importlib.import_module(f'configs.{config_file}')
config = getattr(module_reg, 'Config', None)
### build model
if not args.sf:
from utils.modules.edt import Network
else:
from utils.modules.edtsf import Network
# # For multi-task model, only build one branch for testing.
# config.MODEL.SCALES = [2] # 2, 3, 4
# config.MODEL.NOISE_LEVELS = [] # 15, 25, 50
# config.MODEL.RAIN_LEVELS = [] # 'L', 'H'
# config.VAL.SCALES = config.MODEL.SCALES # 2, 3, 4
# config.VAL.NOISE_LEVELS = config.MODEL.NOISE_LEVELS # 15, 25, 50
# config.VAL.RAIN_LEVELS = config.MODEL.RAIN_LEVELS # 'L', 'H'
model = Network(config)
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
model = model.to(device)
# For multi-task model, only load one branch using filter.
# Optional values of filter_list: 'x2', 'x3', 'x4', 'g15', 'g25', 'g50', 'dr_L', 'dr_H'.
load_model_filter_list(model, args.model, filter_list=[])
# load_model_filter_list(model, args.model, filter_list=['x3', 'x4'])
### load images
legal_types = ['.png', '.jpg', '.tif']
if args.input:
ipath_l = []
for f in sorted(os.listdir(args.input)):
# print("fffffffffff",f)
if os.path.splitext(f)[1] in legal_types:
ipath_l.append(os.path.join(args.input, f))
if args.gt:
gpath_l = []
for f in sorted(os.listdir(args.gt)):
if os.path.splitext(f)[1] in legal_types:
gpath_l.append(os.path.join(args.gt, f))
if args.noise_level:
ipath_l = gpath_l # produce lq by adding noise to gt
### inference
model.eval()
with torch.no_grad():
scales = [] # upsampling sclaes
to_ys = [] # convert to y channel or not
bds = [] # crop boundary pixels
for s in config.VAL.SCALES:
scales.append(s)
to_ys.append(True)
bds.append(s)
for nl in config.VAL.NOISE_LEVELS:
scales.append(1)
to_ys.append(False)
bds.append(0)
for rl in config.VAL.RAIN_LEVELS:
scales.append(1)
to_ys.append(True)
bds.append(0)
all_tasks = config.VAL.SCALES + config.VAL.NOISE_LEVELS + config.VAL.RAIN_LEVELS
psnr_l = [[] for _ in all_tasks]
ssim_l = [[] for _ in all_tasks]
# for batch=1
for idx, lq_path in enumerate(ipath_l):
print("idx",idx)
print("lq_path",lq_path)
if idx<100:
img_name = lq_path[-13:]
else:
img_name = lq_path[-10:]
# img_name = f.split('/')[-1]
# img_name = lq_path[-13:]
print("img_name",img_name)
lq_img = cv2.imread(lq_path, cv2.IMREAD_COLOR).astype(np.float32)
if args.noise_level:
noise = np.random.normal(loc=0.0, scale=args.noise_level, size=lq_img.shape)
lq_img = lq_img + noise
lq_img = np.transpose(lq_img[:, :, ::-1], (2, 0, 1)) / 255.0
lq_img = torch.from_numpy(lq_img).float().unsqueeze(0)
lq_imgs = [lq_img.to(device)]
lqs = []
h_olds = []
w_olds = []
for s, lq_img in zip(scales, lq_imgs):
_, _, h_old, w_old = lq_img.size()
if s > 1:
window_size = lcm(config.MODEL.WINDOW_SIZE)
else:
window_size = lcm(config.MODEL.WINDOW_SIZE) * 2 ** config.MODEL.DEPTH
h_pad = (h_old // window_size + 1) * window_size - h_old
w_pad = (w_old // window_size + 1) * window_size - w_old
lq_img = torch.cat([lq_img, torch.flip(lq_img, [2])], 2)[:, :, :h_old + h_pad, :]
lq_img = torch.cat([lq_img, torch.flip(lq_img, [3])], 3)[:, :, :, :w_old + w_pad]
lqs.append(lq_img)
h_olds.append(h_old)
w_olds.append(w_old)
preds = model(lqs)
outputs = []
for pred, s, h_old, w_old in zip(preds, scales, h_olds, w_olds):
outputs.append(tensor2img(pred[..., :h_old * s, : w_old * s]))
# print("output",outputs)
if args.output:
cv2.imwrite(os.path.join(args.output, img_name), outputs[0])
if args.gt:
gts = [cv2.imread(gpath_l[idx]), cv2.IMREAD_COLOR]
for i, (to_y, bd, output, gt) in enumerate(zip(to_ys, bds, outputs, gts)):
psnr, ssim = calculate_psnr_ssim(output, gt, to_y=to_y, bd=bd)
psnr_l[i].append(psnr)
ssim_l[i].append(ssim)
if args.gt:
avg_psnr, avg_ssim = [], []
for psnr, ssim in zip(psnr_l, ssim_l):
avg_psnr.append(sum(psnr) / len(psnr))
avg_ssim.append(sum(ssim) / len(ssim))
for i, (ta, psnr, ssim) in enumerate(zip(all_tasks, avg_psnr, avg_ssim)):
print(f'[Val Result - {ta}] PSNR: {psnr:.4f}, SSIM: {ssim:.4f}')