-
Notifications
You must be signed in to change notification settings - Fork 19
/
zoom_video_composer.py
executable file
·413 lines (382 loc) · 11.9 KB
/
zoom_video_composer.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#!/usr/bin/env python3
# ZoomVideoComposer
# https://github.com/mwydmuch/ZoomVideoComposer
# Copyright (c) 2023 Marek Wydmuch and the respective contributors
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import concurrent
import os
import shutil
import time
from concurrent.futures import ThreadPoolExecutor
from hashlib import md5
from multiprocessing import cpu_count
import click
from tqdm import tqdm
from helpers import *
VERSION = "0.4.0"
@click.command()
@click.argument(
"image_paths",
nargs=-1,
type=click.Path(exists=True),
required=True,
)
@click.option(
"-a",
"--audio-path",
type=click.Path(exists=True, dir_okay=False),
default=None,
help="Audio file path that will be added to the video.",
)
@click.option(
"-z",
"--zoom",
type=float,
default=2.0,
help="Zoom factor/ratio between images.",
show_default=True,
)
@click.option(
"-d",
"--duration",
type=float,
default=10.0,
help="Duration of the video in seconds.",
show_default=True,
)
@click.option(
"-e",
"--easing",
type=click.Choice(list(EASING_FUNCTIONS.keys())),
default=DEFAULT_EASING_KEY,
help="Easing function.",
show_default=True,
)
@click.option(
"--easing-power",
type=float,
default=DEFAULT_EASING_POWER,
help="Power argument of easeInPow, easeOutPow and easeInOutPow easing functions.",
show_default=True,
)
@click.option(
"--ease-duration",
type=float,
default=DEFAULT_EASE_DURATION,
help="Duration of easing in linearWithInOutEase as a fraction of video duration.",
show_default=True,
)
@click.option(
"-D",
"--direction",
type=click.Choice(["in", "out", "inout", "outin"]),
default="out",
help="Zoom direction. Inout and outin combine both directions.",
show_default=True,
)
@click.option(
"-f",
"--fps",
type=int,
default=30,
help="Frames per second of the output video.",
show_default=True,
)
@click.option(
"-w",
"--width",
type=float,
default=1,
help="Width of the output video. Values > 1 are interpreted as specific sizes in pixels. Values <= 1 are "
"interpreted as a fraction of the width of the first image.",
show_default=True,
)
@click.option(
"-h",
"--height",
type=float,
default=1,
help="Height of the output video. Values > 1 are interpreted as specific sizes in pixels. Values <= 1 are "
"interpreted as a fraction of the height of the first image.",
show_default=True,
)
@click.option(
"-s",
"--resampling",
type=click.Choice(list(RESAMPLING_FUNCTIONS_PIL.keys())),
default=DEFAULT_RESAMPLING_KEY,
help="Resampling technique to use when resizing images.",
show_default=True,
)
@click.option(
"-S",
"--super-sampling",
type=float,
default=1.0,
help="Scales the images by the provided factor. Values > 1 may increase the smoothness of the animation, "
"when using very slow zooms. They increase the duration of the rendering.",
show_default=True,
)
@click.option(
"-m",
"--margin",
type=float,
default=0.05,
help="Size of the margin to cut from the edges of each image for better blending with the next/previous image. "
"Values > 1 are interpreted as specific sizes in pixels. Values <= 1 are interpreted as a fraction of the "
"smaller size of the first image.",
show_default=True,
)
@click.option(
"-o",
"--output",
type=click.Path(),
default="output.mp4",
help="Output video file.",
show_default=True,
)
@click.option(
"-t",
"--threads",
type=int,
default=-1,
help="Number of threads to use to generate frames. Use values <= 0 for number of available threads on your "
"machine minus the provided absolute value.",
show_default=True,
)
@click.option(
"--tmp-dir",
type=click.Path(),
default="tmp",
help="Temporary directory to store frames.",
show_default=True,
)
@click.option(
"--keep-frames",
is_flag=True,
default=False,
help="Keep frames in the temporary directory. Otherwise, it will be deleted after the video is generated.",
show_default=True,
)
@click.option(
"--skip-video-generation",
is_flag=True,
default=False,
help="Skip video generation. Useful if you only want to generate the frames. This option will keep the temporary "
"directory similar to --keep-frames flag.",
show_default=True,
)
@click.option(
"--reverse-images",
is_flag=True,
default=False,
help="Reverse the order of the images.",
show_default=True,
)
@click.option(
"--image-engine",
type=click.Choice(list(IMAGE_CLASSES.keys())),
default=DEFAULT_IMAGE_ENGINE,
help="Image engine to use for image processing.",
show_default=True,
)
@click.option(
"--resume",
is_flag=True,
default=False,
help="Resume generation of the video.",
show_default=True,
)
@click.option(
"--blend-images-only",
is_flag=True,
default=False,
help="Stops after blending the input images. "
"Inspecting the blended images is useful to detect any image-shifts or other artefacts before generating the video.",
show_default=True,
)
def zoom_video_composer_cli(
image_paths,
audio_path=None,
zoom=2.0,
duration=10.0,
easing=DEFAULT_EASING_KEY,
easing_power=DEFAULT_EASING_POWER,
ease_duration=DEFAULT_EASE_DURATION,
direction="out",
fps=30,
reverse_images=False,
width=1,
height=1,
resampling=DEFAULT_RESAMPLING_KEY,
super_sampling=1.0,
margin=0.05,
output="output.mp4",
threads=-1,
tmp_dir="tmp",
keep_frames=False,
skip_video_generation=False,
image_engine=DEFAULT_IMAGE_ENGINE,
resume=False,
blend_images_only=False,
):
"""Compose a zoom video from multiple provided images."""
zoom_video_composer(
image_paths,
audio_path,
zoom,
duration,
easing,
easing_power,
ease_duration,
direction,
fps,
reverse_images,
width,
height,
resampling,
super_sampling,
margin,
output,
threads,
tmp_dir,
keep_frames,
skip_video_generation,
image_engine,
resume,
blend_images_only,
)
def zoom_video_composer(
image_paths,
audio_path=None,
zoom=2.0,
duration=10.0,
easing=DEFAULT_EASING_KEY,
easing_power=DEFAULT_EASING_POWER,
ease_duration=DEFAULT_EASE_DURATION,
direction="out",
fps=30,
reverse_images=False,
width=1,
height=1,
resampling=DEFAULT_RESAMPLING_KEY,
super_sampling=1.0,
margin=0.05,
output="output.mp4",
threads=-1,
tmp_dir="tmp",
keep_frames=False,
skip_video_generation=False,
image_engine=DEFAULT_IMAGE_ENGINE,
resume=False,
blend_images_only=False,
logger=click.echo,
):
start_time = time.time()
"""Compose a zoom video from multiple provided images."""
video_params = f"zoom={zoom}, fps={fps}, dur={duration}, easing={easing}, easing_power={easing_power}, ease_duration={ease_duration}, direction={direction}, resampling={resampling}, margin={margin}, width={width}, height={height}, super_sampling={super_sampling}"
logger(f"Starting zoom video composition with parameters:\n{video_params}")
# Read images
image_paths = get_image_paths(image_paths)
logger(f"Reading {len(image_paths)} image files ...")
images = read_images(image_paths, logger, image_engine)
# Setup some additional variables
easing_func = get_easing_function(easing, easing_power, ease_duration)
resampling_func = get_resampling_function(resampling, image_engine)
num_images = len(images) - 1
num_frames = int(duration * fps)
num_frames_half = int(num_frames / 2)
video_params_to_hash = video_params + "".join(image_paths)
tmp_dir_hash = os.path.join(
tmp_dir, md5(video_params_to_hash.encode("utf-8")).hexdigest()
)
# Calculate sizes based on arguments
width, height, margin = get_sizes(images[0], width, height, margin)
# Create tmp dir
if not os.path.exists(tmp_dir_hash):
logger(f"Creating temporary directory for frames: {tmp_dir_hash} ...")
os.makedirs(tmp_dir_hash, exist_ok=True)
# Reverse images
images = images_reverse(images, direction, reverse_images)
# Blend images (take care of margins)
logger(f"Blending {len(images)} images ...")
images = blend_images(images, margin, zoom, resampling_func)
# Stop here if only blending images
if blend_images_only:
blended_images_path = os.path.join(tmp_dir_hash, "blended_images")
images = images_reverse(images, direction, False)
save_images(images, blended_images_path, files_prefix="blended_")
logger(f"Blended images written to {blended_images_path}. All done!")
return
if super_sampling != 1.0:
logger(f"Super sampling images {super_sampling} ...")
images = resize_images(images, super_sampling, resampling_func)
# Create frames
n_jobs = threads if threads > 0 else cpu_count() - threads
logger(f"Creating frames in {n_jobs} threads ...")
start_frame = 0
if resume:
while os.path.exists(os.path.join(tmp_dir_hash, f"{start_frame:06d}.png")):
start_frame += 1
with ThreadPoolExecutor(max_workers=n_jobs) as executor:
futures = [
executor.submit(
process_frame,
i,
images,
direction,
easing_func,
num_frames,
num_frames_half,
num_images,
zoom,
width,
height,
resampling_func,
tmp_dir_hash,
)
for i in range(start_frame, num_frames)
]
try:
completed = concurrent.futures.as_completed(futures)
for _ in tqdm(
range(num_frames - start_frame), desc="Generating the frames"
):
completed.__next__()
except KeyboardInterrupt:
executor.shutdown(wait=False, cancel_futures=True)
raise
# Images are no longer needed
del images
# Create video clip using images in tmp dir and audio if provided
if skip_video_generation:
logger("Skipping video generation. All done!")
return
else:
logger(f"Writting video in {n_jobs} threads to: {output} ...")
create_video_clip(output, fps, num_frames, tmp_dir_hash, audio_path, n_jobs)
# Remove tmp dir
if not keep_frames:
logger(f"Removing temporary directory: {tmp_dir_hash} ...")
shutil.rmtree(tmp_dir_hash, ignore_errors=False, onerror=None)
if not os.listdir(tmp_dir):
os.rmdir(tmp_dir)
logger(f"Total time: {round(time.time() - start_time, 2)}s")
logger("All done!")
return output
if __name__ == "__main__":
zoom_video_composer_cli()