Skip to content

Commit 06bb471

Browse files
authored
save results
1 parent b9a4b25 commit 06bb471

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

test.py

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import os, shutil, cv2
2+
import numpy as np
3+
import torch
4+
from torchvision import transforms
5+
from unet import UNet
6+
from datasets import custom_test_dataset
7+
import config as cfg
8+
9+
res_dir = cfg.res_dir
10+
11+
if os.path.exists(res_dir):
12+
shutil.rmtree(res_dir)
13+
14+
if not os.path.exists(res_dir):
15+
os.mkdir(res_dir)
16+
17+
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
18+
print('device: ', device)
19+
20+
transform = transforms.Compose([transforms.ToPILImage(), transforms.ToTensor()])
21+
22+
test_dir = cfg.test_dir
23+
test_dataset = custom_test_dataset(test_dir, transform = transform)
24+
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size = cfg.test_bs, shuffle = not True)
25+
26+
print('\nlen(test_dataset) : ', len(test_dataset))
27+
print('len(test_loader) : {} @bs={}'.format(len(test_loader), cfg.test_bs))
28+
29+
# defining the model
30+
model = UNet(n_classes = 1, depth = 3, padding = True).to(device)
31+
32+
ckpt_path = os.path.join(cfg.models_dir, cfg.ckpt)
33+
ckpt = torch.load(ckpt_path)
34+
print(f'\nckpt loaded: {ckpt_path}')
35+
model_state_dict = ckpt['model_state_dict']
36+
model.load_state_dict(model_state_dict)
37+
model.to(device)
38+
39+
def get_img_strip(tensr):
40+
# shape: [bs,1,h,w]
41+
bs, _ , h, w = tensr.shape
42+
tensr2np = (tensr.cpu().numpy().clip(0,1)*255).astype(np.uint8)
43+
canvas = np.ones((h, w*bs), dtype = np.uint8)
44+
for i in range(tensr.shape[0]):
45+
patch_to_paste = tensr2np[i, 0, :, :]
46+
canvas[:, i*w: (i+1)*w] = patch_to_paste
47+
return canvas
48+
49+
def denoise(noisy_imgs, out):
50+
noisy_imgs = get_img_strip(noisy_imgs)
51+
out = get_img_strip(out)
52+
denoised = np.concatenate((noisy_imgs, out), axis = 0)
53+
return denoised
54+
55+
print('\nDenoising noisy images...')
56+
model.eval()
57+
with torch.no_grad():
58+
for batch_idx, noisy_imgs in enumerate(test_loader):
59+
print('batch: {}/{}'.format(str(batch_idx + 1).zfill(len(str(len(test_loader)))), len(test_loader)), end='\r')
60+
noisy_imgs = noisy_imgs.to(device)
61+
out = model(noisy_imgs)
62+
denoised = denoise(noisy_imgs, out)
63+
denoised = denoised
64+
cv2.imwrite(os.path.join(res_dir, f'denoised{str(batch_idx).zfill(3)}.jpg'), denoised)
65+
66+
print('\n\nresults saved in \'{}\' directory'.format(res_dir))

0 commit comments

Comments
 (0)