-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathpredict.py
95 lines (82 loc) · 2.86 KB
/
predict.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
#PyTorch lib
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.utils.data as Data
import torch.nn.functional as F
import torchvision
#Tools lib
import numpy as np
import cv2
import random
import time
import os
import argparse
#Models lib
from models import *
#Metrics lib
from metrics import calc_psnr, calc_ssim
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--mode", type=str)
parser.add_argument("--input_dir", type=str)
parser.add_argument("--output_dir", type=str)
parser.add_argument("--gt_dir", type=str)
args = parser.parse_args()
return args
def align_to_four(img):
#print ('before alignment, row = %d, col = %d'%(img.shape[0], img.shape[1]))
#align to four
a_row = int(img.shape[0]/4)*4
a_col = int(img.shape[1]/4)*4
img = img[0:a_row, 0:a_col]
#print ('after alignment, row = %d, col = %d'%(img.shape[0], img.shape[1]))
return img
def predict(image):
image = np.array(image, dtype='float32')/255.
image = image.transpose((2, 0, 1))
image = image[np.newaxis, :, :, :]
image = torch.from_numpy(image)
image = Variable(image).cuda()
out = model(image)[-1]
out = out.cpu().data
out = out.numpy()
out = out.transpose((0, 2, 3, 1))
out = out[0, :, :, :]*255.
return out
if __name__ == '__main__':
args = get_args()
model = Generator().cuda()
model.load_state_dict(torch.load('./weights/gen.pkl'))
if args.mode == 'demo':
input_list = sorted(os.listdir(args.input_dir))
num = len(input_list)
for i in range(num):
print ('Processing image: %s'%(input_list[i]))
img = cv2.imread(args.input_dir + input_list[i])
img = align_to_four(img)
result = predict(img)
img_name = input_list[i].split('.')[0]
cv2.imwrite(args.output_dir + img_name + '.jpg', result)
elif args.mode == 'test':
input_list = sorted(os.listdir(args.input_dir))
gt_list = sorted(os.listdir(args.gt_dir))
num = len(input_list)
cumulative_psnr = 0
cumulative_ssim = 0
for i in range(num):
print ('Processing image: %s'%(input_list[i]))
img = cv2.imread(args.input_dir + input_list[i])
gt = cv2.imread(args.gt_dir + gt_list[i])
img = align_to_four(img)
gt = align_to_four(gt)
result = predict(img)
result = np.array(result, dtype = 'uint8')
cur_psnr = calc_psnr(result, gt)
cur_ssim = calc_ssim(result, gt)
print('PSNR is %.4f and SSIM is %.4f'%(cur_psnr, cur_ssim))
cumulative_psnr += cur_psnr
cumulative_ssim += cur_ssim
print('In testing dataset, PSNR is %.4f and SSIM is %.4f'%(cumulative_psnr/num, cumulative_ssim/num))
else:
print ('Mode Invalid!')