MonsterMMORPG commited on
Commit
71d8af1
·
1 Parent(s): d42c4c8

Upload video_blend_x.py

Browse files
Files changed (1) hide show
  1. video_blend_x.py +318 -0
video_blend_x.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import platform
4
+ import struct
5
+ import subprocess
6
+ import time
7
+ from typing import List
8
+
9
+ import cv2
10
+ import numpy as np
11
+ import torch.multiprocessing as mp
12
+ from numba import njit
13
+
14
+ import blender.histogram_blend as histogram_blend
15
+ from blender.guide import (BaseGuide, ColorGuide, EdgeGuide, PositionalGuide,
16
+ TemporalGuide)
17
+ from blender.poisson_fusion import poisson_fusion
18
+ from blender.video_sequence import VideoSequence
19
+ from flow.flow_utils import flow_calc
20
+ from src.video_util import frame_to_video
21
+
22
+ OPEN_EBSYNTH_LOG = True
23
+ MAX_PROCESS = 8
24
+
25
+ os_str = platform.system()
26
+
27
+ if os_str == 'Windows':
28
+ ebsynth_bin = '.\\deps\\ebsynth\\bin\\ebsynth.exe'
29
+ elif os_str == 'Linux':
30
+ ebsynth_bin = './deps/ebsynth/bin/ebsynth'
31
+ elif os_str == 'Darwin':
32
+ ebsynth_bin = './deps/ebsynth/bin/ebsynth.app'
33
+ else:
34
+ print('Cannot recognize OS. Run Ebsynth failed.')
35
+ exit(0)
36
+
37
+
38
+ @njit
39
+ def g_error_mask_loop(H, W, dist1, dist2, output, weight1, weight2):
40
+ for i in range(H):
41
+ for j in range(W):
42
+ if weight1 * dist1[i, j] < weight2 * dist2[i, j]:
43
+ output[i, j] = 0
44
+ else:
45
+ output[i, j] = 1
46
+ if weight1 == 0:
47
+ output[i, j] = 0
48
+ elif weight2 == 0:
49
+ output[i, j] = 1
50
+
51
+
52
+ def g_error_mask(dist1, dist2, weight1=1, weight2=1):
53
+ H, W = dist1.shape
54
+ output = np.empty_like(dist1, dtype=np.byte)
55
+ g_error_mask_loop(H, W, dist1, dist2, output, weight1, weight2)
56
+ return output
57
+
58
+
59
+ def create_sequence(base_dir, beg, end, interval, key_dir):
60
+ sequence = VideoSequence(base_dir, beg, end, interval, 'video', key_dir,
61
+ 'tmp', '%04d.png', '%04d.png')
62
+ return sequence
63
+
64
+
65
+ def process_one_sequence(i, video_sequence: VideoSequence):
66
+ interval = video_sequence.interval
67
+ for is_forward in [True, False]:
68
+ input_seq = video_sequence.get_input_sequence(i, is_forward)
69
+ output_seq = video_sequence.get_output_sequence(i, is_forward)
70
+ flow_seq = video_sequence.get_flow_sequence(i, is_forward)
71
+ key_img_id = i if is_forward else i + 1
72
+ key_img = video_sequence.get_key_img(key_img_id)
73
+ for j in range(interval - 1):
74
+ i1 = cv2.imread(input_seq[j])
75
+ i2 = cv2.imread(input_seq[j + 1])
76
+ flow_calc.get_flow(i1, i2, flow_seq[j])
77
+
78
+ guides: List[BaseGuide] = [
79
+ ColorGuide(input_seq),
80
+ EdgeGuide(input_seq,
81
+ video_sequence.get_edge_sequence(i, is_forward)),
82
+ TemporalGuide(key_img, output_seq, flow_seq,
83
+ video_sequence.get_temporal_sequence(i, is_forward)),
84
+ PositionalGuide(flow_seq,
85
+ video_sequence.get_pos_sequence(i, is_forward))
86
+ ]
87
+ weights = [6, 0.5, 0.5, 2]
88
+ for j in range(interval):
89
+ # key frame
90
+ if j == 0:
91
+ img = cv2.imread(key_img)
92
+ cv2.imwrite(output_seq[0], img)
93
+ else:
94
+ cmd = f'{ebsynth_bin} -style {os.path.abspath(key_img)}'
95
+ for g, w in zip(guides, weights):
96
+ cmd += ' ' + g.get_cmd(j, w)
97
+
98
+ cmd += (f' -output {os.path.abspath(output_seq[j])}'
99
+ ' -searchvoteiters 12 -patchmatchiters 6')
100
+ if OPEN_EBSYNTH_LOG:
101
+ print(cmd)
102
+ subprocess.run(cmd,
103
+ shell=True,
104
+ capture_output=not OPEN_EBSYNTH_LOG)
105
+
106
+
107
+ def process_sequences(i_arr, video_sequence: VideoSequence):
108
+ for i in i_arr:
109
+ process_one_sequence(i, video_sequence)
110
+
111
+
112
+ def run_ebsynth(video_sequence: VideoSequence):
113
+
114
+ beg = time.time()
115
+
116
+ processes = []
117
+ mp.set_start_method('spawn')
118
+
119
+ n_process = min(MAX_PROCESS, video_sequence.n_seq)
120
+ cnt = video_sequence.n_seq // n_process
121
+ remainder = video_sequence.n_seq % n_process
122
+
123
+ prev_idx = 0
124
+
125
+ for i in range(n_process):
126
+ task_cnt = cnt + 1 if i < remainder else cnt
127
+ i_arr = list(range(prev_idx, prev_idx + task_cnt))
128
+ prev_idx += task_cnt
129
+ p = mp.Process(target=process_sequences, args=(i_arr, video_sequence))
130
+ p.start()
131
+ processes.append(p)
132
+ for p in processes:
133
+ p.join()
134
+
135
+ end = time.time()
136
+
137
+ print(f'ebsynth: {end-beg}')
138
+
139
+
140
+ @njit
141
+ def assemble_min_error_img_loop(H, W, a, b, error_mask, out):
142
+ for i in range(H):
143
+ for j in range(W):
144
+ if error_mask[i, j] == 0:
145
+ out[i, j] = a[i, j]
146
+ else:
147
+ out[i, j] = b[i, j]
148
+
149
+
150
+ def assemble_min_error_img(a, b, error_mask):
151
+ H, W = a.shape[0:2]
152
+ out = np.empty_like(a)
153
+ assemble_min_error_img_loop(H, W, a, b, error_mask, out)
154
+ return out
155
+
156
+
157
+ def load_error(bin_path, img_shape):
158
+ img_size = img_shape[0] * img_shape[1]
159
+ with open(bin_path, 'rb') as fp:
160
+ bytes = fp.read()
161
+
162
+ read_size = struct.unpack('q', bytes[:8])
163
+ assert read_size[0] == img_size
164
+ float_res = struct.unpack('f' * img_size, bytes[8:])
165
+ res = np.array(float_res,
166
+ dtype=np.float32).reshape(img_shape[0], img_shape[1])
167
+ return res
168
+
169
+
170
+ def process_seq(video_sequence: VideoSequence,
171
+ i,
172
+ blend_histogram=True,
173
+ blend_gradient=True):
174
+
175
+ key1_img = cv2.imread(video_sequence.get_key_img(i))
176
+ img_shape = key1_img.shape
177
+ interval = video_sequence.interval
178
+ beg_id = video_sequence.get_sequence_beg_id(i)
179
+
180
+ oas = video_sequence.get_output_sequence(i)
181
+ obs = video_sequence.get_output_sequence(i, False)
182
+
183
+ binas = [x.replace('jpg', 'bin') for x in oas]
184
+ binbs = [x.replace('jpg', 'bin') for x in obs]
185
+
186
+ obs = [obs[0]] + list(reversed(obs[1:]))
187
+ inputs = video_sequence.get_input_sequence(i)
188
+ oas = [cv2.imread(x) for x in oas]
189
+ obs = [cv2.imread(x) for x in obs]
190
+ inputs = [cv2.imread(x) for x in inputs]
191
+ flow_seq = video_sequence.get_flow_sequence(i)
192
+
193
+ dist1s = []
194
+ dist2s = []
195
+ for i in range(interval - 1):
196
+ bin_a = binas[i + 1]
197
+ bin_b = binbs[i + 1]
198
+ dist1s.append(load_error(bin_a, img_shape))
199
+ dist2s.append(load_error(bin_b, img_shape))
200
+
201
+ lb = 0
202
+ ub = 1
203
+ beg = time.time()
204
+ p_mask = None
205
+
206
+ # write key img
207
+ blend_out_path = video_sequence.get_blending_img(beg_id)
208
+ cv2.imwrite(blend_out_path, key1_img)
209
+
210
+ for i in range(interval - 1):
211
+ c_id = beg_id + i + 1
212
+ blend_out_path = video_sequence.get_blending_img(c_id)
213
+
214
+ dist1 = dist1s[i]
215
+ dist2 = dist2s[i]
216
+ oa = oas[i + 1]
217
+ ob = obs[i + 1]
218
+ weight1 = i / (interval - 1) * (ub - lb) + lb
219
+ weight2 = 1 - weight1
220
+ mask = g_error_mask(dist1, dist2, weight1, weight2)
221
+ if p_mask is not None:
222
+ flow_path = flow_seq[i]
223
+ flow = flow_calc.get_flow(inputs[i], inputs[i + 1], flow_path)
224
+ p_mask = flow_calc.warp(p_mask, flow, 'nearest')
225
+ mask = p_mask | mask
226
+ p_mask = mask
227
+
228
+ # Save tmp mask
229
+ # out_mask = np.expand_dims(mask, 2)
230
+ # cv2.imwrite(f'mask/mask_{c_id:04d}.jpg', out_mask * 255)
231
+
232
+ min_error_img = assemble_min_error_img(oa, ob, mask)
233
+ if blend_histogram:
234
+ hb_res = histogram_blend.blend(oa, ob, min_error_img,
235
+ (1 - weight1), (1 - weight2))
236
+
237
+ else:
238
+ # hb_res = min_error_img
239
+ tmpa = oa.astype(np.float32)
240
+ tmpb = ob.astype(np.float32)
241
+ hb_res = (1 - weight1) * tmpa + (1 - weight2) * tmpb
242
+
243
+ # cv2.imwrite(blend_out_path, hb_res)
244
+
245
+ # gradient blend
246
+ if blend_gradient:
247
+ res = poisson_fusion(hb_res, oa, ob, mask)
248
+ else:
249
+ res = hb_res
250
+
251
+ cv2.imwrite(blend_out_path, res)
252
+ end = time.time()
253
+ print('others:', end - beg)
254
+
255
+
256
+ def main(args):
257
+ global MAX_PROCESS
258
+ MAX_PROCESS = args.n_proc
259
+
260
+ video_sequence = create_sequence(f'{args.name}', args.beg, args.end,
261
+ args.itv, args.key)
262
+ if not args.ne:
263
+ run_ebsynth(video_sequence)
264
+ blend_histogram = True
265
+ blend_gradient = args.ps
266
+ for i in range(video_sequence.n_seq):
267
+ process_seq(video_sequence, i, blend_histogram, blend_gradient)
268
+ if args.output:
269
+ frame_to_video(args.output, video_sequence.blending_dir, args.fps,
270
+ False)
271
+ if not args.tmp:
272
+ video_sequence.remove_out_and_tmp()
273
+
274
+
275
+ if __name__ == '__main__':
276
+ parser = argparse.ArgumentParser()
277
+ parser.add_argument('name', type=str, help='Path to input video')
278
+ parser.add_argument('--output',
279
+ type=str,
280
+ default=None,
281
+ help='Path to output video')
282
+ parser.add_argument('--fps',
283
+ type=float,
284
+ default=30,
285
+ help='The FPS of output video')
286
+ parser.add_argument('--beg',
287
+ type=int,
288
+ default=1,
289
+ help='The index of the first frame to be stylized')
290
+ parser.add_argument('--end',
291
+ type=int,
292
+ default=101,
293
+ help='The index of the last frame to be stylized')
294
+ parser.add_argument('--itv',
295
+ type=int,
296
+ default=10,
297
+ help='The interval of key frame')
298
+ parser.add_argument('--key',
299
+ type=str,
300
+ default='keys0',
301
+ help='The subfolder name of stylized key frames')
302
+ parser.add_argument('--n_proc',
303
+ type=int,
304
+ default=8,
305
+ help='The max process count')
306
+ parser.add_argument('-ps',
307
+ action='store_true',
308
+ help='Use poisson gradient blending')
309
+ parser.add_argument(
310
+ '-ne',
311
+ action='store_true',
312
+ help='Do not run ebsynth (use previous ebsynth output)')
313
+ parser.add_argument('-tmp',
314
+ action='store_true',
315
+ help='Keep temporary output')
316
+
317
+ args = parser.parse_args()
318
+ main(args)