-
Notifications
You must be signed in to change notification settings - Fork 16
/
test.py
102 lines (77 loc) · 3.34 KB
/
test.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
# coding: utf-8
import os
import numpy as np
import torch
from torch import nn
from torchvision import transforms
from tools.config import TEST_SOTS_ROOT, OHAZE_ROOT
from tools.utils import AvgMeter, check_mkdir, sliding_forward
from model import DM2FNet, DM2FNet_woPhy
from datasets import SotsDataset, OHazeDataset
from torch.utils.data import DataLoader
from skimage.metrics import peak_signal_noise_ratio, structural_similarity
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
torch.manual_seed(2018)
torch.cuda.set_device(0)
ckpt_path = './ckpt'
# exp_name = 'RESIDE_ITS'
exp_name = 'O-Haze'
args = {
# 'snapshot': 'iter_40000_loss_0.01230_lr_0.000000',
'snapshot': 'iter_19000_loss_0.04261_lr_0.000014',
}
to_test = {
# 'SOTS': TEST_SOTS_ROOT,
'O-Haze': OHAZE_ROOT,
}
to_pil = transforms.ToPILImage()
def main():
with torch.no_grad():
criterion = nn.L1Loss().cuda()
for name, root in to_test.items():
if 'SOTS' in name:
net = DM2FNet().cuda()
dataset = SotsDataset(root)
elif 'O-Haze' in name:
net = DM2FNet_woPhy().cuda()
dataset = OHazeDataset(root, 'test')
else:
raise NotImplementedError
# net = nn.DataParallel(net)
if len(args['snapshot']) > 0:
print('load snapshot \'%s\' for testing' % args['snapshot'])
net.load_state_dict(torch.load(os.path.join(ckpt_path, exp_name, args['snapshot'] + '.pth')))
net.eval()
dataloader = DataLoader(dataset, batch_size=1)
psnrs, ssims = [], []
loss_record = AvgMeter()
for idx, data in enumerate(dataloader):
# haze_image, _, _, _, fs = data
haze, gts, fs = data
# print(haze.shape, gts.shape)
check_mkdir(os.path.join(ckpt_path, exp_name,
'(%s) %s_%s' % (exp_name, name, args['snapshot'])))
haze = haze.cuda()
if 'O-Haze' in name:
res = sliding_forward(net, haze).detach()
else:
res = net(haze).detach()
loss = criterion(res, gts.cuda())
loss_record.update(loss.item(), haze.size(0))
for i in range(len(fs)):
r = res[i].cpu().numpy().transpose([1, 2, 0])
gt = gts[i].cpu().numpy().transpose([1, 2, 0])
psnr = peak_signal_noise_ratio(gt, r)
psnrs.append(psnr)
ssim = structural_similarity(gt, r, data_range=1, multichannel=True,
gaussian_weights=True, sigma=1.5, use_sample_covariance=False)
ssims.append(ssim)
print('predicting for {} ({}/{}) [{}]: PSNR {:.4f}, SSIM {:.4f}'
.format(name, idx + 1, len(dataloader), fs[i], psnr, ssim))
for r, f in zip(res.cpu(), fs):
to_pil(r).save(
os.path.join(ckpt_path, exp_name,
'(%s) %s_%s' % (exp_name, name, args['snapshot']), '%s.png' % f))
print(f"[{name}] L1: {loss_record.avg:.6f}, PSNR: {np.mean(psnrs):.6f}, SSIM: {np.mean(ssims):.6f}")
if __name__ == '__main__':
main()