-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
VideoClip.py
1487 lines (1205 loc) · 47.3 KB
/
VideoClip.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Implements VideoClip (base class for video clips) and its main subclasses:
- Animated clips: VideoFileClip, ImageSequenceClip, BitmapClip
- Static image clips: ImageClip, ColorClip, TextClip,
"""
import copy as _copy
import os
import subprocess as sp
import tempfile
import numpy as np
import proglog
from imageio import imread, imsave
from PIL import Image
from moviepy.Clip import Clip
from moviepy.config import IMAGEMAGICK_BINARY
from moviepy.decorators import (
add_mask_if_none,
apply_to_mask,
convert_masks_to_RGB,
convert_parameter_to_seconds,
convert_path_to_string,
outplace,
requires_duration,
requires_fps,
use_clip_fps_by_default,
)
from moviepy.tools import (
cross_platform_popen_params,
extensions_dict,
find_extension,
subprocess_call,
)
from moviepy.video.io.ffmpeg_writer import ffmpeg_write_video
from moviepy.video.io.gif_writers import (
write_gif,
write_gif_with_image_io,
write_gif_with_tempfiles,
)
from moviepy.video.tools.drawing import blit
class VideoClip(Clip):
"""Base class for video clips.
See ``VideoFileClip``, ``ImageClip`` etc. for more user-friendly classes.
Parameters
----------
is_mask
`True` if the clip is going to be used as a mask.
Attributes
----------
size
The size of the clip, (width,height), in pixels.
w, h
The width and height of the clip, in pixels.
is_mask
Boolean set to `True` if the clip is a mask.
make_frame
A function ``t-> frame at time t`` where ``frame`` is a
w*h*3 RGB array.
mask (default None)
VideoClip mask attached to this clip. If mask is ``None``,
The video clip is fully opaque.
audio (default None)
An AudioClip instance containing the audio of the video clip.
pos
A function ``t->(x,y)`` where ``x,y`` is the position
of the clip when it is composed with other clips.
See ``VideoClip.set_pos`` for more details
relative_pos
See variable ``pos``.
layer
Indicates which clip is rendered on top when two clips overlap in
a CompositeVideoClip. The highest number is rendered on top.
Default is 0.
"""
def __init__(
self, make_frame=None, is_mask=False, duration=None, has_constant_size=True
):
super().__init__()
self.mask = None
self.audio = None
self.pos = lambda t: (0, 0)
self.relative_pos = False
self.layer = 0
if make_frame:
self.make_frame = make_frame
self.size = self.get_frame(0).shape[:2][::-1]
self.is_mask = is_mask
self.has_constant_size = has_constant_size
if duration is not None:
self.duration = duration
self.end = duration
@property
def w(self):
"""Returns the width of the video."""
return self.size[0]
@property
def h(self):
"""Returns the height of the video."""
return self.size[1]
@property
def aspect_ratio(self):
"""Returns the aspect ratio of the video."""
return self.w / float(self.h)
@property
@requires_duration
@requires_fps
def n_frames(self):
"""Returns the number of frames of the video."""
return int(self.duration * self.fps)
def __copy__(self):
"""Mixed copy of the clip.
Returns a shallow copy of the clip whose mask and audio will
be shallow copies of the clip's mask and audio if they exist.
This method is intensively used to produce new clips every time
there is an outplace transformation of the clip (clip.resize,
clip.subclip, etc.)
Acts like a deepcopy except for the fact that readers and other
possible unpickleables objects are not copied.
"""
cls = self.__class__
new_clip = cls.__new__(cls)
for attr in self.__dict__:
value = getattr(self, attr)
if attr in ("mask", "audio"):
value = _copy.copy(value)
setattr(new_clip, attr, value)
return new_clip
copy = __copy__
# ===============================================================
# EXPORT OPERATIONS
@convert_parameter_to_seconds(["t"])
@convert_masks_to_RGB
def save_frame(self, filename, t=0, with_mask=True):
"""Save a clip's frame to an image file.
Saves the frame of clip corresponding to time ``t`` in ``filename``.
``t`` can be expressed in seconds (15.35), in (min, sec),
in (hour, min, sec), or as a string: '01:03:05.35'.
Parameters
----------
filename : str
Name of the file in which the frame will be stored.
t : float or tuple or str, optional
Moment of the frame to be saved. As default, the first frame will be
saved.
with_mask : bool, optional
If is ``True`` the mask is saved in the alpha layer of the picture
(only works with PNGs).
"""
im = self.get_frame(t)
if with_mask and self.mask is not None:
mask = 255 * self.mask.get_frame(t)
im = np.dstack([im, mask]).astype("uint8")
else:
im = im.astype("uint8")
imsave(filename, im)
@requires_duration
@use_clip_fps_by_default
@convert_masks_to_RGB
@convert_path_to_string(["filename", "temp_audiofile", "temp_audiofile_path"])
def write_videofile(
self,
filename,
fps=None,
codec=None,
bitrate=None,
audio=True,
audio_fps=44100,
preset="medium",
audio_nbytes=4,
audio_codec=None,
audio_bitrate=None,
audio_bufsize=2000,
temp_audiofile=None,
temp_audiofile_path="",
remove_temp=True,
write_logfile=False,
threads=None,
ffmpeg_params=None,
logger="bar",
pixel_format=None,
):
"""Write the clip to a videofile.
Parameters
----------
filename
Name of the video file to write in, as a string or a path-like object.
The extension must correspond to the "codec" used (see below),
or simply be '.avi' (which will work with any codec).
fps
Number of frames per second in the resulting video file. If None is
provided, and the clip has an fps attribute, this fps will be used.
codec
Codec to use for image encoding. Can be any codec supported
by ffmpeg. If the filename is has extension '.mp4', '.ogv', '.webm',
the codec will be set accordingly, but you can still set it if you
don't like the default. For other extensions, the output filename
must be set accordingly.
Some examples of codecs are:
- ``'libx264'`` (default codec for file extension ``.mp4``)
makes well-compressed videos (quality tunable using 'bitrate').
- ``'mpeg4'`` (other codec for extension ``.mp4``) can be an alternative
to ``'libx264'``, and produces higher quality videos by default.
- ``'rawvideo'`` (use file extension ``.avi``) will produce
a video of perfect quality, of possibly very huge size.
- ``png`` (use file extension ``.avi``) will produce a video
of perfect quality, of smaller size than with ``rawvideo``.
- ``'libvorbis'`` (use file extension ``.ogv``) is a nice video
format, which is completely free/ open source. However not
everyone has the codecs installed by default on their machine.
- ``'libvpx'`` (use file extension ``.webm``) is tiny a video
format well indicated for web videos (with HTML5). Open source.
audio
Either ``True``, ``False``, or a file name.
If ``True`` and the clip has an audio clip attached, this
audio clip will be incorporated as a soundtrack in the movie.
If ``audio`` is the name of an audio file, this audio file
will be incorporated as a soundtrack in the movie.
audio_fps
frame rate to use when generating the sound.
temp_audiofile
the name of the temporary audiofile, as a string or path-like object,
to be created and then used to write the complete video, if any.
temp_audiofile_path
the location that the temporary audiofile is placed, as a
string or path-like object. Defaults to the current working directory.
audio_codec
Which audio codec should be used. Examples are 'libmp3lame'
for '.mp3', 'libvorbis' for 'ogg', 'libfdk_aac':'m4a',
'pcm_s16le' for 16-bit wav and 'pcm_s32le' for 32-bit wav.
Default is 'libmp3lame', unless the video extension is 'ogv'
or 'webm', at which case the default is 'libvorbis'.
audio_bitrate
Audio bitrate, given as a string like '50k', '500k', '3000k'.
Will determine the size/quality of audio in the output file.
Note that it mainly an indicative goal, the bitrate won't
necessarily be the this in the final file.
preset
Sets the time that FFMPEG will spend optimizing the compression.
Choices are: ultrafast, superfast, veryfast, faster, fast, medium,
slow, slower, veryslow, placebo. Note that this does not impact
the quality of the video, only the size of the video file. So
choose ultrafast when you are in a hurry and file size does not
matter.
threads
Number of threads to use for ffmpeg. Can speed up the writing of
the video on multicore computers.
ffmpeg_params
Any additional ffmpeg parameters you would like to pass, as a list
of terms, like ['-option1', 'value1', '-option2', 'value2'].
write_logfile
If true, will write log files for the audio and the video.
These will be files ending with '.log' with the name of the
output file in them.
logger
Either ``"bar"`` for progress bar or ``None`` or any Proglog logger.
pixel_format
Pixel format for the output video file.
Examples
--------
>>> from moviepy import VideoFileClip
>>> clip = VideoFileClip("myvideo.mp4").subclip(100,120)
>>> clip.write_videofile("my_new_video.mp4")
>>> clip.close()
"""
name, ext = os.path.splitext(os.path.basename(filename))
ext = ext[1:].lower()
logger = proglog.default_bar_logger(logger)
if codec is None:
try:
codec = extensions_dict[ext]["codec"][0]
except KeyError:
raise ValueError(
"MoviePy couldn't find the codec associated "
"with the filename. Provide the 'codec' "
"parameter in write_videofile."
)
if audio_codec is None:
if ext in ["ogv", "webm"]:
audio_codec = "libvorbis"
else:
audio_codec = "libmp3lame"
elif audio_codec == "raw16":
audio_codec = "pcm_s16le"
elif audio_codec == "raw32":
audio_codec = "pcm_s32le"
audiofile = audio if isinstance(audio, str) else None
make_audio = (
(audiofile is None) and (audio is True) and (self.audio is not None)
)
if make_audio and temp_audiofile:
# The audio will be the clip's audio
audiofile = temp_audiofile
elif make_audio:
audio_ext = find_extension(audio_codec)
audiofile = os.path.join(
temp_audiofile_path,
name + Clip._TEMP_FILES_PREFIX + "wvf_snd.%s" % audio_ext,
)
# enough cpu for multiprocessing ? USELESS RIGHT NOW, WILL COME AGAIN
# enough_cpu = (multiprocessing.cpu_count() > 1)
logger(message="Moviepy - Building video %s." % filename)
if make_audio:
self.audio.write_audiofile(
audiofile,
audio_fps,
audio_nbytes,
audio_bufsize,
audio_codec,
bitrate=audio_bitrate,
write_logfile=write_logfile,
logger=logger,
)
ffmpeg_write_video(
self,
filename,
fps,
codec,
bitrate=bitrate,
preset=preset,
write_logfile=write_logfile,
audiofile=audiofile,
threads=threads,
ffmpeg_params=ffmpeg_params,
logger=logger,
pixel_format=pixel_format,
)
if remove_temp and make_audio:
if os.path.exists(audiofile):
os.remove(audiofile)
logger(message="Moviepy - video ready %s" % filename)
@requires_duration
@use_clip_fps_by_default
@convert_masks_to_RGB
def write_images_sequence(
self, name_format, fps=None, with_mask=True, logger="bar"
):
"""Writes the videoclip to a sequence of image files.
Parameters
----------
name_format
A filename specifying the numerotation format and extension
of the pictures. For instance "frame%03d.png" for filenames
indexed with 3 digits and PNG format. Also possible:
"some_folder/frame%04d.jpeg", etc.
fps
Number of frames per second to consider when writing the
clip. If not specified, the clip's ``fps`` attribute will
be used if it has one.
with_mask
will save the clip's mask (if any) as an alpha canal (PNGs only).
logger
Either ``"bar"`` for progress bar or ``None`` or any Proglog logger.
Returns
-------
names_list
A list of all the files generated.
Notes
-----
The resulting image sequence can be read using e.g. the class
``ImageSequenceClip``.
"""
logger = proglog.default_bar_logger(logger)
# Fails on GitHub macos CI
# logger(message="Moviepy - Writing frames %s." % name_format)
timings = np.arange(0, self.duration, 1.0 / fps)
filenames = []
for i, t in logger.iter_bar(t=list(enumerate(timings))):
name = name_format % i
filenames.append(name)
self.save_frame(name, t, with_mask=with_mask)
# logger(message="Moviepy - Done writing frames %s." % name_format)
return filenames
@requires_duration
@convert_masks_to_RGB
@convert_path_to_string("filename")
def write_gif(
self,
filename,
fps=None,
program="imageio",
opt="nq",
fuzz=1,
loop=0,
dispose=False,
colors=None,
tempfiles=False,
logger="bar",
pixel_format=None,
):
"""Write the VideoClip to a GIF file.
Converts a VideoClip into an animated GIF using ImageMagick
or ffmpeg.
Parameters
----------
filename
Name of the resulting gif file, as a string or a path-like object.
fps
Number of frames per second (see note below). If it
isn't provided, then the function will look for the clip's
``fps`` attribute (VideoFileClip, for instance, have one).
program
Software to use for the conversion, either 'imageio' (this will use
the library FreeImage through ImageIO), or 'ImageMagick', or 'ffmpeg'.
opt
Optimalization to apply. If program='imageio', opt must be either 'wu'
(Wu) or 'nq' (Neuquant). If program='ImageMagick',
either 'optimizeplus' or 'OptimizeTransparency'.
fuzz
(ImageMagick only) Compresses the GIF by considering that
the colors that are less than fuzz% different are in fact
the same.
tempfiles
Writes every frame to a file instead of passing them in the RAM.
Useful on computers with little RAM. Can only be used with
ImageMagick' or 'ffmpeg'.
progress_bar
If True, displays a progress bar
pixel_format
Pixel format for the output gif file. If is not specified
'rgb24' will be used as the default format unless ``clip.mask``
exist, then 'rgba' will be used. This option is only going to
be accepted if ``program=ffmpeg`` or when ``tempfiles=True``
Notes
-----
The gif will be playing the clip in real time (you can
only change the frame rate). If you want the gif to be played
slower than the clip you will use ::
>>> # slow down clip 50% and make it a gif
>>> myClip.multiply_speed(0.5).to_gif('myClip.gif')
"""
# A little sketchy at the moment, maybe move all that in write_gif,
# refactor a little... we will see.
if program == "imageio":
write_gif_with_image_io(
self,
filename,
fps=fps,
opt=opt,
loop=loop,
colors=colors,
logger=logger,
)
elif tempfiles:
# convert imageio opt variable to something that can be used with
# ImageMagick
opt = "optimizeplus" if opt == "nq" else "OptimizeTransparency"
write_gif_with_tempfiles(
self,
filename,
fps=fps,
program=program,
opt=opt,
fuzz=fuzz,
loop=loop,
dispose=dispose,
colors=colors,
logger=logger,
pixel_format=pixel_format,
)
else:
# convert imageio opt variable to something that can be used with
# ImageMagick
opt = "optimizeplus" if opt == "nq" else "OptimizeTransparency"
write_gif(
self,
filename,
fps=fps,
program=program,
opt=opt,
fuzz=fuzz,
loop=loop,
dispose=dispose,
colors=colors,
logger=logger,
pixel_format=pixel_format,
)
# -----------------------------------------------------------------
# F I L T E R I N G
def subfx(self, fx, start_time=0, end_time=None, **kwargs):
"""Apply a transformation to a part of the clip.
Returns a new clip in which the function ``fun`` (clip->clip)
has been applied to the subclip between times `start_time` and `end_time`
(in seconds).
Examples
--------
>>> # The scene between times t=3s and t=6s in ``clip`` will be
>>> # be played twice slower in ``new_clip``
>>> new_clip = clip.subapply(lambda c:c.multiply_speed(0.5) , 3,6)
"""
left = None if (start_time == 0) else self.subclip(0, start_time)
center = self.subclip(start_time, end_time).fx(fx, **kwargs)
right = None if (end_time is None) else self.subclip(start_time=end_time)
clips = [clip for clip in [left, center, right] if clip is not None]
# beurk, have to find other solution
from moviepy.video.compositing.concatenate import concatenate_videoclips
return concatenate_videoclips(clips).with_start(self.start)
# IMAGE FILTERS
def image_transform(self, image_func, apply_to=None):
"""Modifies the images of a clip by replacing the frame `get_frame(t)` by
another frame, `image_func(get_frame(t))`.
"""
apply_to = apply_to or []
return self.transform(lambda get_frame, t: image_func(get_frame(t)), apply_to)
# --------------------------------------------------------------
# C O M P O S I T I N G
def fill_array(self, pre_array, shape=(0, 0)):
"""TODO: needs documentation."""
pre_shape = pre_array.shape
dx = shape[0] - pre_shape[0]
dy = shape[1] - pre_shape[1]
post_array = pre_array
if dx < 0:
post_array = pre_array[: shape[0]]
elif dx > 0:
x_1 = [[[1, 1, 1]] * pre_shape[1]] * dx
post_array = np.vstack((pre_array, x_1))
if dy < 0:
post_array = post_array[:, : shape[1]]
elif dy > 0:
x_1 = [[[1, 1, 1]] * dy] * post_array.shape[0]
post_array = np.hstack((post_array, x_1))
return post_array
def blit_on(self, picture, t):
"""Returns the result of the blit of the clip's frame at time `t`
on the given `picture`, the position of the clip being given
by the clip's ``pos`` attribute. Meant for compositing.
"""
wf, hf = picture.size
ct = t - self.start # clip time
# GET IMAGE AND MASK IF ANY
img = self.get_frame(ct).astype("uint8")
im_img = Image.fromarray(img)
if self.mask is not None:
mask = (self.mask.get_frame(ct) * 255).astype("uint8")
im_mask = Image.fromarray(mask).convert("L")
if im_img.size != im_mask.size:
bg_size = (
max(im_img.size[0], im_mask.size[0]),
max(im_img.size[1], im_mask.size[1]),
)
im_img_bg = Image.new("RGB", bg_size, "black")
im_img_bg.paste(im_img, (0, 0))
im_mask_bg = Image.new("L", bg_size, 0)
im_mask_bg.paste(im_mask, (0, 0))
im_img, im_mask = im_img_bg, im_mask_bg
else:
im_mask = None
wi, hi = im_img.size
# SET POSITION
pos = self.pos(ct)
# preprocess short writings of the position
if isinstance(pos, str):
pos = {
"center": ["center", "center"],
"left": ["left", "center"],
"right": ["right", "center"],
"top": ["center", "top"],
"bottom": ["center", "bottom"],
}[pos]
else:
pos = list(pos)
# is the position relative (given in % of the clip's size) ?
if self.relative_pos:
for i, dim in enumerate([wf, hf]):
if not isinstance(pos[i], str):
pos[i] = dim * pos[i]
if isinstance(pos[0], str):
D = {"left": 0, "center": (wf - wi) / 2, "right": wf - wi}
pos[0] = D[pos[0]]
if isinstance(pos[1], str):
D = {"top": 0, "center": (hf - hi) / 2, "bottom": hf - hi}
pos[1] = D[pos[1]]
pos = map(int, pos)
return blit(im_img, picture, pos, mask=im_mask)
def add_mask(self):
"""Add a mask VideoClip to the VideoClip.
Returns a copy of the clip with a completely opaque mask
(made of ones). This makes computations slower compared to
having a None mask but can be useful in many cases. Choose
Set ``constant_size`` to `False` for clips with moving
image size.
"""
if self.has_constant_size:
mask = ColorClip(self.size, 1.0, is_mask=True)
return self.with_mask(mask.with_duration(self.duration))
else:
def make_frame(t):
return np.ones(self.get_frame(t).shape[:2], dtype=float)
mask = VideoClip(is_mask=True, make_frame=make_frame)
return self.with_mask(mask.with_duration(self.duration))
def on_color(self, size=None, color=(0, 0, 0), pos=None, col_opacity=None):
"""Place the clip on a colored background.
Returns a clip made of the current clip overlaid on a color
clip of a possibly bigger size. Can serve to flatten transparent
clips.
Parameters
----------
size
Size (width, height) in pixels of the final clip.
By default it will be the size of the current clip.
color
Background color of the final clip ([R,G,B]).
pos
Position of the clip in the final clip. 'center' is the default
col_opacity
Parameter in 0..1 indicating the opacity of the colored
background.
"""
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
if size is None:
size = self.size
if pos is None:
pos = "center"
if col_opacity is not None:
colorclip = ColorClip(
size, color=color, duration=self.duration
).with_opacity(col_opacity)
result = CompositeVideoClip([colorclip, self.with_position(pos)])
else:
result = CompositeVideoClip(
[self.with_position(pos)], size=size, bg_color=color
)
if (
isinstance(self, ImageClip)
and (not hasattr(pos, "__call__"))
and ((self.mask is None) or isinstance(self.mask, ImageClip))
):
new_result = result.to_ImageClip()
if result.mask is not None:
new_result.mask = result.mask.to_ImageClip()
return new_result.with_duration(result.duration)
return result
@outplace
def with_make_frame(self, mf):
"""Change the clip's ``get_frame``.
Returns a copy of the VideoClip instance, with the make_frame
attribute set to `mf`.
"""
self.make_frame = mf
self.size = self.get_frame(0).shape[:2][::-1]
@outplace
def with_audio(self, audioclip):
"""Attach an AudioClip to the VideoClip.
Returns a copy of the VideoClip instance, with the `audio`
attribute set to ``audio``, which must be an AudioClip instance.
"""
self.audio = audioclip
@outplace
def with_mask(self, mask):
"""Set the clip's mask.
Returns a copy of the VideoClip with the mask attribute set to
``mask``, which must be a greyscale (values in 0-1) VideoClip.
"""
assert mask is None or mask.is_mask
self.mask = mask
@add_mask_if_none
@outplace
def with_opacity(self, opacity):
"""Set the opacity/transparency level of the clip.
Returns a semi-transparent copy of the clip where the mask is
multiplied by ``op`` (any float, normally between 0 and 1).
"""
self.mask = self.mask.image_transform(lambda pic: opacity * pic)
@apply_to_mask
@outplace
def with_position(self, pos, relative=False):
"""Set the clip's position in compositions.
Sets the position that the clip will have when included
in compositions. The argument ``pos`` can be either a couple
``(x,y)`` or a function ``t-> (x,y)``. `x` and `y` mark the
location of the top left corner of the clip, and can be
of several types.
Examples
--------
>>> clip.with_position((45,150)) # x=45, y=150
>>>
>>> # clip horizontally centered, at the top of the picture
>>> clip.with_position(("center","top"))
>>>
>>> # clip is at 40% of the width, 70% of the height:
>>> clip.with_position((0.4,0.7), relative=True)
>>>
>>> # clip's position is horizontally centered, and moving up !
>>> clip.with_position(lambda t: ('center', 50+t) )
"""
self.relative_pos = relative
if hasattr(pos, "__call__"):
self.pos = pos
else:
self.pos = lambda t: pos
@apply_to_mask
@outplace
def with_layer(self, layer):
"""Set the clip's layer in compositions. Clips with a greater ``layer``
attribute will be displayed on top of others.
Note: Only has effect when the clip is used in a CompositeVideoClip.
"""
self.layer = layer
# --------------------------------------------------------------
# CONVERSIONS TO OTHER TYPES
@convert_parameter_to_seconds(["t"])
def to_ImageClip(self, t=0, with_mask=True, duration=None):
"""
Returns an ImageClip made out of the clip's frame at time ``t``,
which can be expressed in seconds (15.35), in (min, sec),
in (hour, min, sec), or as a string: '01:03:05.35'.
"""
new_clip = ImageClip(self.get_frame(t), is_mask=self.is_mask, duration=duration)
if with_mask and self.mask is not None:
new_clip.mask = self.mask.to_ImageClip(t)
return new_clip
def to_mask(self, canal=0):
"""Return a mask a video clip made from the clip."""
if self.is_mask:
return self
else:
new_clip = self.image_transform(lambda pic: 1.0 * pic[:, :, canal] / 255)
new_clip.is_mask = True
return new_clip
def to_RGB(self):
"""Return a non-mask video clip made from the mask video clip."""
if self.is_mask:
new_clip = self.image_transform(
lambda pic: np.dstack(3 * [255 * pic]).astype("uint8")
)
new_clip.is_mask = False
return new_clip
else:
return self
# ----------------------------------------------------------------
# Audio
@outplace
def without_audio(self):
"""Remove the clip's audio.
Return a copy of the clip with audio set to None.
"""
self.audio = None
@outplace
def afx(self, fun, *args, **kwargs):
"""Transform the clip's audio.
Return a new clip whose audio has been transformed by ``fun``.
"""
self.audio = self.audio.fx(fun, *args, **kwargs)
class DataVideoClip(VideoClip):
"""
Class of video clips whose successive frames are functions
of successive datasets
Parameters
----------
data
A liste of datasets, each dataset being used for one frame of the clip
data_to_frame
A function d -> video frame, where d is one element of the list `data`
fps
Number of frames per second in the animation
"""
def __init__(self, data, data_to_frame, fps, is_mask=False, has_constant_size=True):
self.data = data
self.data_to_frame = data_to_frame
self.fps = fps
def make_frame(t):
return self.data_to_frame(self.data[int(self.fps * t)])
VideoClip.__init__(
self,
make_frame,
is_mask=is_mask,
duration=1.0 * len(data) / fps,
has_constant_size=has_constant_size,
)
class UpdatedVideoClip(VideoClip):
"""
Class of clips whose make_frame requires some objects to
be updated. Particularly practical in science where some
algorithm needs to make some steps before a new frame can
be generated.
UpdatedVideoClips have the following make_frame:
>>> def make_frame(t):
>>> while self.world.clip_t < t:
>>> world.update() # updates, and increases world.clip_t
>>> return world.to_frame()
Parameters
----------
world
An object with the following attributes:
- world.clip_t: the clip's time corresponding to the world's state.
- world.update() : update the world's state, (including increasing
world.clip_t of one time step).
- world.to_frame() : renders a frame depending on the world's state.
is_mask
True if the clip is a WxH mask with values in 0-1
duration
Duration of the clip, in seconds
"""
def __init__(self, world, is_mask=False, duration=None):
self.world = world
def make_frame(t):
while self.world.clip_t < t:
world.update()
return world.to_frame()
VideoClip.__init__(
self, make_frame=make_frame, is_mask=is_mask, duration=duration
)
"""---------------------------------------------------------------------
ImageClip (base class for all 'static clips') and its subclasses
ColorClip and TextClip.
I would have liked to put these in a separate file but Python is bad
at cyclic imports.
---------------------------------------------------------------------"""