-
Notifications
You must be signed in to change notification settings - Fork 13
/
FRVSRGAN_Test.py
219 lines (183 loc) · 8.1 KB
/
FRVSRGAN_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
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"""
This file does a quick check of a trained FRVSR-GAN model on a single low resolution video source and upscales it to 4x.
Aman Chadha | aman@amanchadha.com
Adapted from FR-SRGAN, MIT 6.819 Advances in Computer Vision, Nov 2018
"""
import argparse
import cv2
import numpy as np
import torch
import torch.nn.functional as func
import matplotlib.pyplot as plt
import DatasetLoader
import FRVSRGAN_Models
from skimage import img_as_ubyte
from skimage.util import img_as_float32
# TODO
verbose = 0
def trunc(tensor):
# tensor = tensor.clone()
tensor[tensor < 0] = 0
tensor[tensor > 1] = 1
return tensor
def test_optic_flow(frame1, frame2):
# im1 = img_as_ubyte(frame1)
# im2 = img_as_ubyte(frame2)
im1 = cv2.imread('im1.png')
im2 = cv2.imread('im2.png')
frame1 = img_as_float32(im1)
frame2 = img_as_float32(im2)
prvs = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)
next = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(prvs, next, None, 0.5, 3, 15, 3, 5, 1.2, 0)
flow[..., 0] /= flow.shape[1] / 2
flow[..., 1] /= flow.shape[0] / 2
flow *= -1
for i in range(flow.shape[0]):
for j in range(flow.shape[1]):
flow[i, j, 0] += (j / flow.shape[1] * 2 - 1)
flow[i, j, 1] += (i / flow.shape[0] * 2 - 1)
print(flow.shape)
torch_frame1 = torch.unsqueeze(torch.tensor(frame1).permute(2, 0, 1), 0)
# print(frame1.shape)
# print(torch_frame1.shape)
# print(torch_frame1)
flow = flow.astype(np.float32, copy=False)
est_frame2 = func.grid_sample(torch_frame1, torch.unsqueeze(torch.tensor(flow), 0))
res_img = img_as_ubyte(est_frame2[0].permute(1, 2, 0).numpy())
cv2.imwrite('est_frame2.png', res_img)
# flow_len = np.expand_dims(np.sqrt((flow[...,0]**2 + flow[...,1]**2)), 2)
# flow /= flow_len
# print(flow)
pass
exit(0)
# cv2.imshow('frame2', rgb)
# k = cv2.waitKey(30) & 0xff
# if k == 27:
# break
# elif k == ord('s'):
# cv2.imwrite('opticalmyhsv.pgm', rgb)
#
# cap.release()
# cv2.destroyAllWindows()
import math
def psnr(img1, img2):
# print(img1.size())
mse = torch.mean((img1 - img2) ** 2)
if mse == 0:
return 100
PIXEL_MAX = 1.0
return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Test Single Video')
# Use FR-SRGAN
parser.add_argument('--model', default='./epochs/netG_epoch_4_7.pth', type=str, help='FRVSRGAN Model')
# Use FRVSR
# parser.add_argument('--model', default='./models/FRVSR.4', type=str, help='FRVSRGAN Model')
opt = parser.parse_args()
UPSCALE_FACTOR = 4
MODEL_NAME = opt.model
with torch.no_grad():
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = FRVSRGAN_Models.FRVSR(0, 0, 0)
model.to(device)
# for cpu
# model.load_state_dict(torch.load('epochs/' + MODEL_NAME, map_location=lambda storage, loc: storage))
checkpoint = torch.load(MODEL_NAME, map_location='cpu')
model.load_state_dict(checkpoint)
model.eval()
# To train on fixed input data (controlled by fixedIndices)
train_loader, val_loader = DatasetLoader.get_data_loaders(batch=1, dataset_size=0, validation_split=1, shuffle_dataset=True, fixedIndices=0)
# Train on a random sample
# train_loader, val_loader = DatasetLoader.get_data_loaders(batch=1, dataset_size=0, validation_split=1, shuffle_dataset=True)
tot_psnr = 0
for idx, (lr_example, hr_example) in enumerate(val_loader, 1):
out_psnr = 0
fps = 6
frame_numbers = 7
# frame_numbers = 100
lr_width = lr_example.shape[4]
lr_height = lr_example.shape[3]
model.set_param(batch_size=1, width=lr_width, height=lr_height)
model.init_hidden(device)
hr_video_size = (lr_width * UPSCALE_FACTOR, lr_height * UPSCALE_FACTOR)
lr_video_size = (lr_width, lr_height)
output_sr_name = 'FRVSRGAN_Out_' + str(UPSCALE_FACTOR) + f'_{idx}_' + 'Random_Sample.mp4'
output_gt_name = 'FRVSRGAN_Out_' + 'GroundTruth' + f'_{idx}_' + 'Random_Sample.mp4'
output_lr_name = 'FRVSRGAN_Out_' + 'LowRes' + '_' + 'Random_Sample.mp4'
output_aw_name = 'FRVSRGAN_Out_' + 'IntermediateWarp' + '_' + 'Random_Sample.mp4'
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
hr_video_writer = cv2.VideoWriter(output_sr_name, fourcc, fps, hr_video_size)
lr_video_writer = cv2.VideoWriter(output_lr_name, fourcc, fps, lr_video_size)
aw_video_writer = cv2.VideoWriter(output_aw_name, fourcc, fps, hr_video_size)
gt_video_writer = cv2.VideoWriter(output_gt_name, fourcc, fps, hr_video_size)
# read frame
# test_optic_flow(lr_example[0][0].permute(1,2,0).numpy(), \
# lr_example[1][0].permute(1,2,0).numpy())
for image, truth in zip(lr_example, hr_example):
# plt.subplot(121)
# plt.imshow(image[0].permute(1,2,0).numpy())
# plt.subplot(122)
# plt.imshow(truth[0].permute(1,2,0).numpy())
# plt.show()
# exit(0)
image.to(device)
if verbose:
print(f'image shape is {image.shape}')
if torch.cuda.is_available():
image = image.cuda()
# apply FRVSR
hr_out, lr_out = model(image)
hr_out = hr_out.clone()
lr_out = image.clone()
# plt.imshow(hr_out[0].permute(1,2,0).detach().numpy())
# plt.imshow(lr_out[0].permute(1,2,0).detach().numpy())
# plt.imshow(truth[0].permute(1,2,0).clone().numpy())
#plt.show() #TODO uncomment
print(image.shape)
print(lr_out.shape)
l1 = torch.mean((truth - hr_out) ** 2)
l2 = torch.mean((image - lr_out) ** 2)
print(l1)
print(l2)
# print(lr_out)
# # print(image)
# hr_out = DatasetLoader.inverse_transform(hr_out.clone())
# lr_out = DatasetLoader.inverse_transform(lr_out.clone())
# image = DatasetLoader.inverse_transform(image.clone())
# truth = DatasetLoader.inverse_transform(truth.clone())
hr_out = trunc(hr_out.clone())
lr_out = trunc(lr_out.clone())
aw_out = trunc(model.afterWarp.clone())
out_psnr += psnr(hr_out, truth)
l1 = torch.mean((truth - hr_out) ** 2)
l2 = torch.mean((image - lr_out) ** 2)
print(l1)
print(l2)
#plt.imshow(hr_out[0].permute(1, 2, 0).detach().numpy())
#plt.imshow(truth[0].permute(1,2,0).clone().numpy())
plt.imshow(lr_out[0].permute(1, 2, 0).detach().numpy())
#plt.show()
def output(out, writer):
out = out.clone()
out_img = out.data[0].numpy()
out_img *= 255.0
out_img = (np.uint8(out_img)).transpose((1, 2, 0))
out_img = cv2.cvtColor(out_img, cv2.COLOR_BGR2RGB)
writer.write(out_img)
# Write the high res video
output(hr_out, hr_video_writer)
# Write the low res video
output(lr_out, lr_video_writer)
# Write the intermediate warped video
output(aw_out, aw_video_writer)
# Write the ground truth video
output(truth, gt_video_writer)
hr_video_writer.release()
lr_video_writer.release()
aw_video_writer.release()
gt_video_writer.release()
print(f"PSNR is {out_psnr / 7}")
tot_psnr = (tot_psnr * (idx - 1) + out_psnr / 7) / idx
break
print(f"Average PSNR is {tot_psnr}")