-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathskymagic.py
270 lines (181 loc) · 8.81 KB
/
skymagic.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
import glob
import argparse
from networks import *
from skyboxengine import *
import utils
import torch
# Decide which device we want to run on
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
parser = argparse.ArgumentParser(description='SKYAR')
parser.add_argument('--path', type=str, default='./config/config-just-skymask.json', metavar='str',
help='configurations')
parser.add_argument('--data_folder', type=str, default='', help='folder to data folder')
parser.add_argument('--output_folder', type=str, default='', help='folder to output folder')
def GetFileNamesRecursive(rootPath, file_types = ['.jpg', '.png']) :
if len(file_types) > 0:
for file_type in file_types:
file_type = file_type.lower()
abs_file_paths = []
for root, dirnames, filenames in os.walk(rootPath):
for filename in filenames:
if len(file_types) > 0:
suffix = os.path.splitext(filename)[-1]
suffix = suffix.lower()
if suffix not in file_types:
continue
abs_file_paths.append(os.path.join(root, filename))
abs_file_paths = sorted(abs_file_paths)
file_paths = []
for file_path in abs_file_paths :
file_path = file_path[len(rootPath) + 1:]
file_paths.append(file_path)
return file_paths, abs_file_paths
class SkyFilter():
def __init__(self, args):
self.ckptdir = args.ckptdir
self.datadir = args.datadir
self.input_mode = args.input_mode
self.in_size_w, self.in_size_h = args.in_size_w, args.in_size_h
self.out_size_w, self.out_size_h = args.out_size_w, args.out_size_h
self.skyboxengine = SkyBox(args)
self.net_G = define_G(input_nc=3, output_nc=1, ngf=64, netG=args.net_G).to(device)
self.load_model()
self.video_writer = cv2.VideoWriter('demo.mp4', cv2.VideoWriter_fourcc(*'MP4V'),
20.0, (args.out_size_w, args.out_size_h))
self.video_writer_cat = cv2.VideoWriter('demo-cat.mp4', cv2.VideoWriter_fourcc(*'MP4V'),
20.0, (2*args.out_size_w, args.out_size_h))
if os.path.exists(args.output_dir) is False:
os.mkdir(args.output_dir)
self.save_jpgs = args.save_jpgs
def load_model(self):
print('loading the best checkpoint...')
checkpoint = torch.load(os.path.join(self.ckptdir, 'best_ckpt.pt'))
# checkpoint = torch.load(os.path.join(self.ckptdir, 'last_ckpt.pt'))
self.net_G.load_state_dict(checkpoint['model_G_state_dict'])
self.net_G.to(device)
self.net_G.eval()
def write_video(self, img_HD, syneth):
frame = np.array(255.0 * syneth[:, :, ::-1], dtype=np.uint8)
self.video_writer.write(frame)
frame_cat = np.concatenate([img_HD, syneth], axis=1)
frame_cat = np.array(255.0 * frame_cat[:, :, ::-1], dtype=np.uint8)
self.video_writer_cat.write(frame_cat)
cv2.imshow('frame_cat', frame_cat)
cv2.waitKey(1)
def synthesize(self, img_HD, img_HD_prev):
h, w, c = img_HD.shape
img = cv2.resize(img_HD, (self.in_size_w, self.in_size_h))
img = np.array(img, dtype=np.float32)
img = torch.tensor(img).permute([2, 0, 1]).unsqueeze(0)
with torch.no_grad():
G_pred = self.net_G(img.to(device))
G_pred = torch.nn.functional.interpolate(G_pred, (h, w), mode='bicubic', align_corners=False)
G_pred = G_pred[0, :].permute([1, 2, 0])
G_pred = torch.cat([G_pred, G_pred, G_pred], dim=-1)
G_pred = np.array(G_pred.detach().cpu())
G_pred = np.clip(G_pred, a_max=1.0, a_min=0.0)
skymask = self.skyboxengine.skymask_refinement(G_pred, img_HD)
syneth = self.skyboxengine.skyblend(img_HD, img_HD_prev, skymask)
return syneth, G_pred, skymask
def cvtcolor_and_resize(self, img_HD):
img_HD = cv2.cvtColor(img_HD, cv2.COLOR_BGR2RGB)
img_HD = np.array(img_HD / 255., dtype=np.float32)
img_HD = cv2.resize(img_HD, (self.out_size_w, self.out_size_h))
return img_HD
def run_imgseq(self):
print('running evaluation...')
img_names = os.listdir(self.datadir)
img_HD_prev = None
for idx in range(len(img_names)):
this_dir = os.path.join(self.datadir, img_names[idx])
img_HD = cv2.imread(this_dir, cv2.IMREAD_COLOR)
img_HD = self.cvtcolor_and_resize(img_HD)
if img_HD_prev is None:
img_HD_prev = img_HD
syneth, G_pred, skymask = self.synthesize(img_HD, img_HD_prev)
if self.save_jpgs:
fpath = os.path.join(args.output_dir, img_names[idx])
plt.imsave(fpath[:-4] + '_input.jpg', img_HD)
plt.imsave(fpath[:-4] + 'coarse_skymask.jpg', G_pred)
plt.imsave(fpath[:-4] + 'refined_skymask.jpg', skymask)
plt.imsave(fpath[:-4] + 'syneth.jpg', syneth.clip(min=0, max=1))
self.write_video(img_HD, syneth)
print('processing: %d / %d ...' % (idx, len(img_names)))
img_HD_prev = img_HD
def run_imgseq_sky_mask(self):
print('running evaluation...')
img_names, img_paths_full = GetFileNamesRecursive(self.datadir)
img_HD_prev = None
for idx in range(len(img_names)):
this_dir = os.path.join(self.datadir, img_names[idx])
img_HD = cv2.imread(this_dir, cv2.IMREAD_COLOR)
img_HD = self.cvtcolor_and_resize(img_HD)
if img_HD_prev is None:
img_HD_prev = img_HD
h, w, c = img_HD.shape
img = cv2.resize(img_HD, (self.in_size_w, self.in_size_h))
img = np.array(img, dtype=np.float32)
img = torch.tensor(img).permute([2, 0, 1]).unsqueeze(0)
with torch.no_grad():
G_pred = self.net_G(img.to(device))
#G_pred = torch.nn.functional.interpolate(G_pred, (h, w))
G_pred = G_pred[0, :].permute([1, 2, 0])
G_pred = torch.cat([G_pred, G_pred, G_pred], dim=-1)
G_pred = np.array(G_pred.detach().cpu())
G_pred = np.clip(G_pred, a_max=1.0, a_min=0.0)
if self.save_jpgs:
fpath = os.path.join(args.output_dir, img_names[idx])
os.makedirs(os.path.abspath(os.path.join(fpath, os.pardir)), exist_ok=True)
# plt.imsave(fpath[:-4] + '_input.jpg', img_HD)
plt.imsave(fpath[:-4] + '_mask.jpg', G_pred)
print('processing: %d / %d ...' % (idx, len(img_names)))
img_HD_prev = img_HD
def run_video(self):
print('running evaluation...')
cap = cv2.VideoCapture(self.datadir)
m_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
img_HD_prev = None
idx = 0
while (1):
ret, frame = cap.read()
if ret:
img_HD = self.cvtcolor_and_resize(frame)
if img_HD_prev is None:
img_HD_prev = img_HD
syneth, G_pred, skymask = self.synthesize(img_HD, img_HD_prev)
if self.save_jpgs:
fpath = os.path.join(args.output_dir, str(idx)+'.jpg')
plt.imsave(fpath[:-4] + '_input.jpg', img_HD)
plt.imsave(fpath[:-4] + '_coarse_skymask.jpg', G_pred)
plt.imsave(fpath[:-4] + '_refined_skymask.jpg', skymask)
plt.imsave(fpath[:-4] + '_syneth.jpg', syneth.clip(min=0, max=1))
self.write_video(img_HD, syneth)
print('processing: %d / %d ...' % (idx, m_frames))
img_HD_prev = img_HD
idx += 1
else: # if reach the last frame
break
def run(self):
if self.input_mode == 'seq':
self.run_imgseq()
elif self.input_mode == 'video':
self.run_video()
elif self.input_mode == 'seq_sky_mask':
self.run_imgseq_sky_mask()
else:
print('wrong input_mode, select one in [seq, video')
exit()
if __name__ == '__main__':
parser = parser.parse_args()
config_path = parser.path
args = utils.parse_config(config_path)
if len(parser.data_folder) :
args.datadir = parser.data_folder
if len(parser.output_folder) :
args.output_dir = parser.output_folder
sf = SkyFilter(args)
sf.run()