Skip to content

Video editing with Python

added decorator convert_masks_to_RGB. MUCH improved docs

Zulkoe60593ca1d8c
diff --git a/README.rst b/README.rst
index b0cc694d..9dfc083f 100644
--- a/README.rst
+++ b/README.rst
@@ -1,7 +1,7 @@
MoviePy
========
-MoviePy (full documentation here_) is a Python module for script-based video editing. It enables basic operations (cuts, concatenations, title insertions) to be done in a few lines, and can be used for video compositing (a.k.a. non-linear editing), video processing, or to create advanced effects. It can read and write all the most common video formats, including GIF.
+MoviePy (full documentation here_) is a Python module for video editing. It enables basic operations (cuts, concatenations, title insertions) to be done in a few lines, and can be used for video compositing (a.k.a. non-linear editing), video processing, or to create advanced effects. It can read and write all the most common video formats, including GIF.
A typical MoviePy script looks like this: ::
diff --git a/docs/advanced_uses/advanced_uses.rst b/docs/advanced_uses/advanced_uses.rst
deleted file mode 100644
index af4b0a83..00000000
--- a/docs/advanced_uses/advanced_uses.rst
+++ /dev/null
@@ -1,190 +0,0 @@
-.. _advanceduses:
-
-Advanced uses of MoviePy
---------------------------
-
-These pages give a few tips, tricks, toughts and tutorials on MoviePy. You can read more about each feature in the documentation (docstring) of each function.
-
-
-When should I use ``moviepy.editor`` ?
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Most examples in this tutorial use the submodule ``moviepy.editor``, but should *you* use it ?
-
-MoviePy can be used in different ways: either directly *by hand* to edit one of your personal videos, or indirectly (used on a webserver, or by another library). In the first case you should use the module ``moviepy.editor``, like this: ::
-
- from moviepy.editor import * # imports everything, quick and dirty
- import moviepy.editor as mpy # then use mpy.VideoFileClip, etc.
- from moviepy.editor import VideoFileClip # just import what you need
-
-With any of these lines, the ``moviepy.editor`` module will actually do a lot of work beind the curtain. It will fetch all the most common classes, functions and subpackages of MoviePy, initialize a PyGame session (if PyGame is installed) to be able to preview video clips, and implement some shortcuts, like adding the ``resize`` transformation to the clips. This way you can use ``clip.resize(width=240)`` instead of the longer ``clip.fx( resize, width=240)``. In short, ``moviepy.editor`` it provides all you need to play around and edit your videos.
-
-However, ``moviepy.editor`` takes time to load (circa one second). So if all you need is one or two features inside another library, it is better to import directly what you need, it writes longer but runs way faster: ::
-
- from moviepy.video.io.VideoFileClip import VideoFileClip
- from moviepy.video.fx.resize import resize
-
-
-Writing your own video tranformations
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-There are several categories of clip modifications in MoviePy.
-
-The very common methods for composition (cutting a clip, setting its position, etc.) are implemented as ``clip.mymethod``. For instance ``clip.subclip(15,20)`` returns the part of ``clip`` that is playing between 15 seconds and 20 seconds.
-
-For all the other modifications, we use ``clip.fx`` and ``clip.fl``. ``clip.fx`` is meant to make it easy to use already-written transformation functions, while ``clip.fl`` makes it easy to write new transformation functions.
-
-Note that none of these methods occur *inplace*: they all create a copy of the clip and let the original clip untouched. Moreover, modified clips are just *special views* of the original clip, they do not carry all the video data with them. Actually, the *real* modifications are only performed when you are rendering the clip (see :ref:`renderingAClip`). This means that all the clip objects that you will create through modifications of other clips take virtually no place in the memory and are created quasi-instantly.
-
-clip.fx
-""""""""
-
-Suppose that you have some functions implementing effects on clips: ::
-
- effect_1(clip, args1) -> new clip
- effect_2(clip, args2) -> new clip
- effect_3(clip, args3) -> new clip
-
-where ``args`` represent arguments and/or keyword arguments. To apply these functions, in that order, to one clip, you would write something like ::
-
- newclip = effect_3( effect_2( effect_1(clip, args3), args2), args1)
-
-but this is not easy to read. To have a clearer syntax you can use ``clip.fx``: ::
-
- newclip = (clip.fx( effect_1, args1)
- .fx( effect_2, args2)
- .fx( effect_3, args3))
-
-Much better ! There are already many effects implemented in the modules ``moviepy.video.fx`` and ``moviepy.audio.fx``. The fx methods in these modules are automatically applied to the sound and the mask of the clip if it is relevant, so that you don't have to worry about modifying these. For practicality, when you use ``from moviepy import.editor *``, these two modules are loaded as ``vfx`` and ``afx``, so you may write something like ::
-
- from moviepy.editor import *
- clip = (VideoFileClip("myvideo.avi")
- .fx( vfx.resize, width=460) # resize (keep aspect ratio)
- .fx( vfx.speedx, 2) # double speed
- .fx( vfx.colorx, 0.5)) # darken the picture
-
-For convenience, when you use ``moviepy.editor``, frequently used methods such as ``resize`` can be called in a simpler way: ``clip.resize(...)`` instead of ``clip.fx( vfx.resize, ...)``
-
-
-clip.fl
-""""""""
-
-
-You can modify a clip as you want using custom *filters* with ``clip.fl_time``, ``clip.fl_image``, and more generally with ``clip.fl``.
-
-You can change the timeline of the clip with ``clip.fl_time`` like this: ::
-
- modifiedClip1 = my_clip.fl_time(lambda t: 3*t)
- modifiedClip2 = my_clip.fl_time(lambda t: 1+sin(t))
-
-Now the clip ``modifiedClip1`` plays the same as ``my_clip``, only three times faster, while ``modifiedClip2`` will play ``my_clip`` by oscillating between the times t=0s and t=2s. Note that in the last case you have created a clip of infinite duration (which is not a problem for the moment).
-
-You can also modify the display of a clip with ``clip.fl_image``. The following takes a clip and inverts the green and blue channels of the frames: ::
-
- def invert_green_blue(image):
- return image[:,:,[0,2,1]]
-
- modifiedClip = my_clip.fl_image( invert_green_blue )
-
-Finally, you may want to process the clip by taking into account both the time and the frame picture. This is possible with the method ``clip.fl(filter)``. The filter must be a function which takes two arguments and returns a picture. the fist argument is a ``get_frame`` method (i.e. a function ``g(t)`` which given a time returns the clip's frame at that time), and the second argument is the time. ::
-
- def scroll(get_frame, t):
- """
- This function returns a 'region' of the current frame.
- The position of this region depends on the time.
- """
- frame = get_frame(t)
- frame_region = frame[int(t):int(t)+360,:]
- return frame_region
-
- modifiedClip = my_clip.fl( scroll )
-
-This will scroll down the clip, with a constant height of 360 pixels.
-
-When programming a new effect, whenever it is possible, prefer using ``fl_time`` and
-``fl_image`` instead of ``fl`` if possible when implementing
-new effects. The reason is that, when these effects are applied to
-ImageClips, MoviePy will recognize that these methods do not need to be applied to each frame, which will
-result in faster renderings.
-
-
-
-
-
-Fast editing tricks with MoviePy
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-When you are editing a video or trying to achieve an effect with MoviePy through a trial and error process, generating the video at each trial can be very long. This section presents a few tricks to go faster.
-
-The first
-
-Most of the time, just having one frame of the video can tell you if you are doing the right thing. To preview just one frame of a clip, if you have PyGame installed, use one of these: ::
-
- my_clip.show() # shows the first frame of the clip
- my_clip.show(10.5) # shows the frame of the clip at t=10.5s
- my_clip.show(interactive = True)
-
-
-If you don't have PyGame, you can still save just one frame to a file: ::
-
- my_clip.save_frame("frame.jpeg") # saves the first frame
- my_clip.save_frame(t=2, "frame.png") # saves the frame a t=2s
-
-And if
-
-
-A clip previewed, i.e. generated and displayed at the same time, which is faster than re-generating the file and opening it every time you change your script. Previewing requires to have the Python package PyGame installed, and will only work if PyGame is initialized, which will be the case
-if you started with ``from moviepy import *``.
-
-
-The last line allows you to click anywhere on the clip and get the position and color of the pixel on which you clicked (press Escape to terminate).
-
-To preview the clip, you must specify the frames-per-second ::
-
- my_clip.preview() # preview with default fps=15
- my_clip.preview(fps=25)
- my_clip.preview(fps=15, audio=False) # don't play sound.
-
-The ``fps`` can be any number, independently of the ``fps`` of your different sources.
-
-
-A few words on Gifmaking
-~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-
-
-Getting pixel coordinates
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Getting the coordinates of pixels of your video can be useful to add text or other videos at this position. There are several ways to get these coordinates, all require PyGame.
-
-The first way is to display one frame of the clip, in an interactive mode: ::
-
- points = my_clip.show(t=2, interactive=True) # show at t=2s
-
-This shows the frame, and it will display the coordinate and color of each pixel you click on. When you press escape, it ends the process and stores the coordinates/pixels in the variable ``points``.
-
-A second method is to use ``clip.preview`` mentioned above.
-
-A third method is to use the dedicated tracking method.
-
-
-While the clip is getting prewieved, just click anywhere on the clip to get the time, position and color of the pixel you clicked.
-
-
-
-
-Using transitions
-~~~~~~~~~~~~~~~~~~~
-
-To be written.
-
-
-Using subtitles
-~~~~~~~~~~~~~~~~
-
-To be written.
-
-
-
-
diff --git a/docs/demo_preview.jpeg b/docs/demo_preview.jpeg
new file mode 100644
index 00000000..7160f512
Binary files /dev/null and b/docs/demo_preview.jpeg differ
diff --git a/docs/gallery.rst b/docs/gallery.rst
index d9862c61..82a70d91 100644
--- a/docs/gallery.rst
+++ b/docs/gallery.rst
@@ -66,7 +66,7 @@ This `tutorial
style="max-width:50%; height:'auto'; display:block; margin-left: auto;margin-right: auto; margin-bottom:30px;" /></a>
-It is possible to combine MoviePy the same with many graphic librairies (like matplotlib, mayavi, pyopengl, etc.).
+It is also possible to combine MoviePy with other graphic librairies like matplotlib, etc.
.. Rinconcam
diff --git a/docs/getting_started/advanced_tools.rst b/docs/getting_started/advanced_tools.rst
index f0272bf2..80393b42 100644
--- a/docs/getting_started/advanced_tools.rst
+++ b/docs/getting_started/advanced_tools.rst
@@ -1,3 +1,5 @@
+.. _advancedtools:
+
Advanced tools
===============
diff --git a/docs/getting_started/circle.gif b/docs/getting_started/circle.gif
new file mode 100644
index 00000000..c00cbd16
Binary files /dev/null and b/docs/getting_started/circle.gif differ
diff --git a/docs/getting_started/clips.rst b/docs/getting_started/clips.rst
index 82d8c90a..f7d7835c 100644
--- a/docs/getting_started/clips.rst
+++ b/docs/getting_started/clips.rst
@@ -1,93 +1,95 @@
-Clips in MoviePy
-==================
+.. _clips:
+Creating and exporting clips
+==============================
+
+Video au audio clips are the central objects of MoviePy. In this section we present the different sorts of clips, how to create them, and how to write them to a file. For informations on modifying a clip (cuts, effects, etc.), see :ref:`effects`. For how to put clips together see :ref:`CompositeVideoClips` and to see how to preview clips before writing a file, refer to :ref:`efficient`.
+
+The following code summarizes the base clips that you can create with moviepy: ::
+
+ # VIDEO CLIPS
+ clip = VideoClip(make_frame, duration=4) # for custom animations (see below)
+ clip = VideoFileClip("my_video_file.mp4") # or .avi, .webm, .gif ...
+ clip = ImageClip("my_picture.png") # or .jpeg, .tiff, ...
+ clip = TextClip("Hello !", font="Amiri-Bold", fontsize=70, color="black")
+ clip = ColorClip(size=(460,380), color=[R,G,B])
+
+ # AUDIO CLIPS
+ clip = AudioFileClip("my_audiofile.mp3") # or .ogg, .wav... or a video !
+ clip = AudioArrayClip(numpy_array, fps=44100) # from a numerical array
+ clip = AudioClip(make_frame, duration=3) # uses a function make_frame(t)
+
+
+
+The best to understand these clips is to read the full documentation for each in the :ref:`reference_manual`. The next sections
In this section we see how to create clips, (for instance from video or audio files), how to mix them together, and how to write them to a file.
-The most common objects in MoviePy are called clips. A clip (let's call it ``my_clip``) can be either an audio clip or a video clip. It has different attributes, like ``my_clip.duration`` (indicating its duration in seconds), ``clip.start`` (indicating the time in seconds where the clip should start playing when mixed with other videos), ``my_clip.w`` (the width in pixel of the clip), etc.
-A video clip ``my_clip`` can have two special attributes which are themselves clips: ``my_clip.audio`` is an audio clip representing the audio track of the vidceo clip. ``my_clip.mask`` is a special kind of video clip which defines the transparency of ``my_clip``.
-A clip also has methods which enable to create a derivative of this clip. For instance ``my_clip.subclip(2,7)`` creates a new clip which is like ``my_clip`` cut between seconds 2 and 7.
+Categories of video clips
+~~~~~~~~~~~~~~~~~~~~~~~~~~
-Classes of video clips
-~~~~~~~~~~~~~~~~~~~~~~
+Video clips are the building blocks of longer videos. Technically, they are clips with a ``clip.get_frame(t)`` method which outputs a HxWx3 numpy array representing the frame of the clip at time *t*. There are two main categories: animated clips (made with ``VideoFileClip`` and ``VideoClip``) and unanimated clips which show the same picture for an a-priori infinite duration (``ImageClip``, ``TextClip``,``ColorClip``). There are also special video clips call masks, which belong to the categories above but output greyscale frames indicating which parts of another clip are visible or not. A video clip can carry around an audio clip (``clip.audio``) which is its *soundtrack*, and a mask clip.
-Video clips are the building blocks of longer videos. They can be created with one of the following:
+VideoClip
+""""""""""
-- ``VideoFileClip('myHolidays.mp4')`` will generate a clip from a video file. This video file can have any format or extension : mp4, flv, mov, ... even gif !
-- ``ImageClip('myPicture.png')`` will generate a clip displaying a picture, for an *a priori* infinite duration.
-- ``ColorClip((height,width),color=(R,G,B))`` generates a special ImageClip of a single color.
-- ``TextClip('Hello folks !',font='Impact-Regular')`` generates a special ImageClip representing a text. The generation of the text image is made by the software ImageMagick (see the Installation section).
+``VideoClip`` is the base class for all the other video clips in MoviePy. If all you want is to edit video files, you will never need it. This class is practical when you want to make animations from frames that are generated by another library. All you need is to define a function ``make_frame(t)`` which returns a HxWx3 numpy array (of 8-bits integers) representing the frame at time t. Here is an example with the graphics library Gizeh: ::
-To that list we should add the ``CompositeVideoClips`` which are obtained by putting several clips together.
+ import gizeh
+ import moviepy.editor as mpy
-.. _CompositeVideoClips:
+ def make_frame(t):
+ surface = gizeh.Surface(128,128) # width, height
+ radius = W*(1+ (t*(2-t))**2 )/6 # the radius varies over time
+ circle = gizeh.circle(radius, xy = (64,64), fill=(1,0,0))
+ circle.draw(surface)
+ return surface.get_npimage() # returns a 8-bit RGB array
-Composite video clips
-~~~~~~~~~~~~~~~~~~~~~
+ clip = mpy.VideoClip(make_frame, duration=2) # 2 seconds
+ clip.write_gif("circle.gif",fps=15)
-Composite video clips are video clips which will display the contents of several other video clips. The simplest compositing is concatenation with :meth:`~moviepy.video.compositing.concatenate.concatenate`: ::
-
- video = concatenate([clip1,clip2,clip3])
+.. image:: circle.gif
+ :width: 128 px
+ :align: center
-Now ``video`` is a clip that plays the clips 1, 2, and 3 one after the other. You can also play a transition clip between the clips with the option ``transition=my_clip``.
+VideoFileClip
+"""""""""""""""
-Next, you have the `~moviepy.video.compositing.CompositeVideoClip.CompositeVideoClip`: ::
-
- video = CompositeVideoClip([clip1,clip2,clip3])
-
-Now ``video`` plays ``clip1``, and ``clip2`` *on top of* ``clip1``, and ``clip3`` on top of ``clip1``, and ``clip2``. For instance, if ``clip2`` and ``clip3`` have the same size as ``clip1``, then only ``clip3``, which is on top, will be visible in the video... unless ``clip3`` and ``clip2`` have masks which hide parts of them. Note that by default the composition has the size of its first clip (as it is generally a *background*). But sometimes you will want to make your clips *float* in a bigger composition, so you will specify the size of the final composition as follows ::
- video = CompositeVideoClip([clip1,clip2,clip3], size=(720,460))
-
-In a CompositionClip, all the clips start to play at a time that is specified by the ``clip.start`` attribute. You can set this starting time as follows: ::
-
- clip1 = clip1.set_start(5) # start after 5 seconds
+ImageClip
+""""""""""
-So for instance your composition will look like ::
- video = CompositeVideoClip([clip1, # starts at t=0
- clip2.set_start(5), # start at t=5s
- clip3.set_start(9)]) # start at t=9s
+TextClip
+"""""""""""""""
-In the example above, maybe ``clip2`` will start before ``clip1`` is over. In this case you can make ``clip2`` appear with a *fade-in* effect of one second: ::
-
- video = CompositeVideoClip([clip1, # starts at t=0
- clip2.set_start(5).fadein(1),
- clip3.set_start(9)])
+Mask clips
+~~~~~~~~~~~~~~
-Finally, if ``clip2`` and ``clip3`` are smaller than ``clip1``, you can decide where they will appear in the composition by setting their position. Here we indicate the coordinates of the top-left pixel: ::
-
- video = CompositeVideoClip([clip1,
- clip2.set_pos((45,150)),
- clip3.set_pos((90,100))])
+when it is composed with other clips (see :ref:CompositeVideoClips)
-Note that there are many ways to specify the position: ::
-
- clip2.set_pos((45,150)) # x=45, y=150 , in pixels
-
- clip2.set_pos("center") # automatically centered
+The fundamental difference is that standard masks output frames with 3 coomposants (R-G-B) per pixel, comprised between 0 and 255, while a mask has just one composant per pixel, between 0 and 1 (1 indicating a fully visible pixel and 0 a transparent pixel).
+
+When you create or load a clip that you will use as a mask you need to declare it: ::
- # clip2 is horizontally centered, and at the top of the picture
- clip2.set_pos(("center","top"))
- # clip2 is vertically centered, at the left of the picture
- clip2.set_pos(("left","center"))
+ mclip = VideoClip(makeframe, duration=4, ismask=True)
+ mclip = ImageClip("my_mask.jpeg", ismask=True)
+ mclip = VideoClip("myvideo.mp4", ismask=True)
- # clip2 is at 40% of the width, 70% of the height of the screen:
- clip2.set_pos((0.4,0.7), relative=True)
- # clip2's position is horizontally centered, and moving down !
- clip2.set_pos(lambda t: ('center', 50+t) )
+In the case of video and image files, if these are not already black and white they will be converted automatically.
-When indicating the position keep in mind that the ``y`` coordinate has its zero at the top of the picture:
-
-.. figure:: videoWH.jpeg
+Any video clip can be turned into a mask with ``clip.to_mask()``, and a mask can be turned to a standard RGB video clip with ``my_mask_clip.to_RGB()``.
.. _renderingAClip:
-Writing a video clip to a file
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Exporting video clips
+~~~~~~~~~~~~~~~~~~~~~~~
+
+Video files (.mp4, .webm, .ogv...)
+""""""""""""""""""""""""""""""""""""
To write a clip as a video file, use ::
@@ -107,41 +109,40 @@ Sometimes it is impossible for MoviePy to guess the ``duration`` attribute of th
my_clip.set_duration(5).write_videofile("flower.mp4") # works !
-Writing an animated GIF
-~~~~~~~~~~~~~~~~~~~~~~~~~
+Animated GIFs
+""""""""""""""
To write your video as an animated GIF, use ::
my_clip.write_gif('test.gif', fps=12)
-If your computer has enough RAM (say, at least 2GB), you can use its faster version ``write_gif2``:
- my_clip.write_gif2('test.gif', fps=12)
+See `this blog post <http://zulko.github.io/blog/2014/01/23/making-animated-gifs-from-video-files-with-python>`_ for informations on making GIFs from video files, and `this other post <http://zulko.github.io/blog/2014/09/20/vector-animations-with-python/>`_ for GIF animations with vector graphics.
+.. _CCaudioClips:
-See `this blog post <http://zulko.github.io/blog/2014/01/23/making-animated-gifs-from-video-files-with-python>`_ for more informations on making GIFs with MoviePy.
-.. _CCaudioClips:
Audio clips
~~~~~~~~~~~~~
-The second important objects of MoviePy are the audio clips. If ``myHolidays.mp4`` is a video with sound, then ::
+When you make a video clip from a video containing a soundtrack, like this: ::
clip = VideoFileClip('myHolidays.mp4')
-will create a clip with a ``clip.audio`` attribute which is an audio clip. This is the sound that you will hear if you render the clip with ``clip.preview`` or ``clip.write_videofile``. You can also create an audio clip from a sound file and then attach it to a video clip: ::
-
- audio = AudioFileClip('mySong.wav')
- video = VideoFileClip('myHolidays.mp4').set_audio(audio)
+The resulting clip has an attribute ``clip.audio`` (its soundtrack) which is an audio clip. You can also set the soundtrack of a video clip with ::
+
+ new_clip = clip.set_audio(some_audio_clip)
-Like video clips, audio clips can be cut (with ``clip.subclip``) modified (with for instance ``clip.volumex`` which multiplies the volume) and combined (with ``CompositeAudioClip``). But most of the time, MoviePy will do that for you:
+In this section we will see that audio clips can be created, imported, exported like video clips.
-- When you cut a video clip with ``videoclip.subclip(20,25)`` then the sound will also be cut, i.e. the resulting clip will have an audio clip ``videoclip.audio.subclip(20,25)``.
-- When you put several clips together in a CompositeVideoClip, then the sound of the CompositeVideoClip will be the composition of the sounds of the different video clips.
-For an example, you can refer to :ref:`soundexample`. Like video clips, sound clips have a ``get_frame`` attribute, and creating new audio clips by modifying or putting together other audio clips does not eat the memory. The actual sounds of the audio clips are only computed when we ask to play them or to write them to a file. You can do that as follows: ::
-
- audioclip.preview() # default fps: 22050
- audioclip.preview(fps=44100)
- audioclip.to_audiofile('my_clip.mp3',fps=44100) #default fps: 22050
\ No newline at end of file
+AudioFileClip
+""""""""""""""
+
+
+AudioArrayClip
+"""""""""""""""
+
+AudioClip
+""""""""""
\ No newline at end of file
diff --git a/docs/getting_started/compositing.rst b/docs/getting_started/compositing.rst
new file mode 100644
index 00000000..aaf1e0c8
--- /dev/null
+++ b/docs/getting_started/compositing.rst
@@ -0,0 +1,129 @@
+.. _CompositeVideoClips:
+
+Mixing clips together
+=======================
+
+Video composition, also known as non-linear editing, is the fact of playing several clips together in a new clip. This video is a good example of what compositing you can do with MoviePy:
+
+.. raw:: html
+
+ <div style="position: relative; padding-bottom: 56.25%; padding-top: 30px; margin-bottom:30px; height: 0; overflow: hidden;
+ display:block; margin-left: auto; margin-right: auto;">
+ <iframe src="http://youtube.com/v/rIehsqqYFEM&hl?rel=0" frameborder="0" allowfullscreen
+ style="position: absolute; top: 0; bottom: 10; width: 70%; height: 100%;">
+ </iframe>
+ </div>
+
+Before starting, note that video clips generally carry an audio track and a mask, which are also clips. When you compose these clips together, the soundtrack and mask of the final clip are automatically generated by putting together the soundtracks and masks of the clips. So most of the time you don't need to worry about mixing the audio and masks.
+
+Stacking and concatenating clips
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Two simple ways of putting clips together is to concatenate them (to play them one after the other in a single long clip) or to stack them (to them side by side in a single larger clip).
+
+Concatenation is done with the function ``concatenate``: ::
+
+ from moviepy.editor import VideoFileClip, concatenate
+ clip1 = VideoFileClip("myvideo.mp4")
+ clip2 = VideoFileClip("myvideo2.mp4").subclip(50,60)
+ clip3 = VideoFileClip("myvideo3.mp4")
+ final_clip = concatenate([clip1,clip2,clip3])
+ final_clip.write_videofile("my_concatenation.mp4")
+
+
+The ``final_clip`` is a clip that plays the clips 1, 2, and 3 one after the other. Note that the clips do not need to be the same size. If they arent's they will all appear centered in a clip large enough to contain the biggest of them, with optionnally a color of your choosing to fill the borders. You have many other options there (see the doc of the function). You can for instance play a transition clip between the clips with the option ``transition=my_clip``.
+
+Stacking is done with ``clip_array``: ::
+
+ from moviepy.editor import VideoFileClip, clips_array, vfx
+ clip1 = VideoFileClip("myvideo.mp4").margin(10) # add 10px contour
+ clip2 = clip1.fx( vfx.mirror_x)
+ clip3 = clip1.fx( vfx.mirror_y)
+ clip4 = clip1.resize(0.60) # downsize 60%
+ final_clip = clips_array([[clip1, clip2],
+ [clip3, clip4]])
+ final_clip.resize(width=480).write_videofile("my_stack.mp4")
+
+You obtain a clip which looks like this:
+
+.. figure:: stacked.jpeg
+
+
+CompositeVideoClips
+~~~~~~~~~~~~~~~~~~~~~
+
+The `CompositeVideoClip` class provides a very flexible way to compose clips, but is more complex than ``concatenate`` and ``clips_array`` ::
+
+ video = CompositeVideoClip([clip1,clip2,clip3])
+
+Now ``video`` plays ``clip1``, and ``clip2`` *on top of* ``clip1``, and ``clip3`` on top of ``clip1``, and ``clip2``. For instance, if ``clip2`` and ``clip3`` have the same size as ``clip1``, then only ``clip3``, which is on top, will be visible in the video... unless ``clip3`` and ``clip2`` have masks which hide parts of them. Note that by default the composition has the size of its first clip (as it is generally a *background*). But sometimes you will want to make your clips *float* in a bigger composition, so you will specify the size of the final composition as follows ::
+
+ video = CompositeVideoClip([clip1,clip2,clip3], size=(720,460))
+
+Starting and stopping times
+""""""""""""""""""""""""""""
+
+In a CompositionClip, all the clips start to play at a time that is specified by the ``clip.start`` attribute. You can set this starting time as follows: ::
+
+ clip1 = clip1.set_start(5) # start after 5 seconds
+
+So for instance your composition will look like ::
+
+ video = CompositeVideoClip([clip1, # starts at t=0
+ clip2.set_start(5), # start at t=5s
+ clip3.set_start(9)]) # start at t=9s
+
+In the example above, maybe ``clip2`` will start before ``clip1`` is over. In this case you can make ``clip2`` appear with a *fade-in* effect of one second: ::
+
+ video = CompositeVideoClip([clip1, # starts at t=0
+ clip2.set_start(5).fadein(1),
+ clip3.set_start(9)])
+
+Positioning clips
+""""""""""""""""""
+
+If ``clip2`` and ``clip3`` are smaller than ``clip1``, you can decide where they will appear in the composition by setting their position. Here we indicate the coordinates of the top-left pixel of the clips: ::
+
+ video = CompositeVideoClip([clip1,
+ clip2.set_pos((45,150)),
+ clip3.set_pos((90,100))])
+
+There are many ways to specify the position: ::
+
+ clip2.set_pos((45,150)) # x=45, y=150 , in pixels
+
+ clip2.set_pos("center") # automatically centered
+
+ # clip2 is horizontally centered, and at the top of the picture
+ clip2.set_pos(("center","top"))
+
+ # clip2 is vertically centered, at the left of the picture
+ clip2.set_pos(("left","center"))
+
+ # clip2 is at 40% of the width, 70% of the height of the screen:
+ clip2.set_pos((0.4,0.7), relative=True)
+
+ # clip2's position is horizontally centered, and moving down !
+ clip2.set_pos(lambda t: ('center', 50+t) )
+
+When indicating the position keep in mind that the ``y`` coordinate has its zero at the top of the picture:
+
+.. figure:: videoWH.jpeg
+
+Transitions
+------------
+
+Everyone loves transitions between clips: fade-ins, fade-out, clips that slide in front of the previous one... everything is good to impress your grandparents.
+
+
+Compositing audio clips
+-------------------------
+
+Audio clips can be mixed together with ``CompositeAudioClip`` and ``concatenate_audioclips``: ::
+
+ from moviepy.editor import *
+ # ... make some clips
+ concat = concatenate_audioclips([aclip1, aclip2, aclip3])
+ compo = CompositeAudioClip([aclip1.volumex(1.2),
+ aclip2.set_start(5),
+ aclip3.set_start(9)])
\ No newline at end of file
diff --git a/docs/getting_started/effects.rst b/docs/getting_started/effects.rst
index 7078c318..4d633711 100644
--- a/docs/getting_started/effects.rst
+++ b/docs/getting_started/effects.rst
@@ -1,2 +1,83 @@
+.. _effects:
+
Clips transformations and effects
-===================================
\ No newline at end of file
+===================================
+
+There are several categories of clip modifications in MoviePy.
+
+The very common methods for composition (cutting a clip, setting its position, etc.) are implemented as ``clip.mymethod``. For instance ``clip.subclip(15,20)`` returns the part of ``clip`` that is playing between 15 seconds and 20 seconds.
+
+For all the other modifications, we use ``clip.fx`` and ``clip.fl``. ``clip.fx`` is meant to make it easy to use already-written transformation functions, while ``clip.fl`` makes it easy to write new transformation functions.
+
+Note that none of these methods occur *inplace*: they all create a copy of the clip and let the original clip untouched. Moreover, modified clips are just *special views* of the original clip, they do not carry all the video data with them. Actually, the *real* modifications are only performed when you are rendering the clip (see :ref:`renderingAClip`). This means that all the clip objects that you will create through modifications of other clips take virtually no place in the memory and are created quasi-instantly.
+
+clip.fx
+""""""""
+
+Suppose that you have some functions implementing effects on clips: ::
+
+ effect_1(clip, args1) -> new clip
+ effect_2(clip, args2) -> new clip
+ effect_3(clip, args3) -> new clip
+
+where ``args`` represent arguments and/or keyword arguments. To apply these functions, in that order, to one clip, you would write something like ::
+
+ newclip = effect_3( effect_2( effect_1(clip, args3), args2), args1)
+
+but this is not easy to read. To have a clearer syntax you can use ``clip.fx``: ::
+
+ newclip = (clip.fx( effect_1, args1)
+ .fx( effect_2, args2)
+ .fx( effect_3, args3))
+
+Much better ! There are already many effects implemented in the modules ``moviepy.video.fx`` and ``moviepy.audio.fx``. The fx methods in these modules are automatically applied to the sound and the mask of the clip if it is relevant, so that you don't have to worry about modifying these. For practicality, when you use ``from moviepy import.editor *``, these two modules are loaded as ``vfx`` and ``afx``, so you may write something like ::
+
+ from moviepy.editor import *
+ clip = (VideoFileClip("myvideo.avi")
+ .fx( vfx.resize, width=460) # resize (keep aspect ratio)
+ .fx( vfx.speedx, 2) # double speed
+ .fx( vfx.colorx, 0.5)) # darken the picture
+
+For convenience, when you use ``moviepy.editor``, frequently used methods such as ``resize`` can be called in a simpler way: ``clip.resize(...)`` instead of ``clip.fx( vfx.resize, ...)``
+
+
+clip.fl
+""""""""
+
+
+You can modify a clip as you want using custom *filters* with ``clip.fl_time``, ``clip.fl_image``, and more generally with ``clip.fl``.
+
+You can change the timeline of the clip with ``clip.fl_time`` like this: ::
+
+ modifiedClip1 = my_clip.fl_time(lambda t: 3*t)
+ modifiedClip2 = my_clip.fl_time(lambda t: 1+sin(t))
+
+Now the clip ``modifiedClip1`` plays the same as ``my_clip``, only three times faster, while ``modifiedClip2`` will play ``my_clip`` by oscillating between the times t=0s and t=2s. Note that in the last case you have created a clip of infinite duration (which is not a problem for the moment).
+
+You can also modify the display of a clip with ``clip.fl_image``. The following takes a clip and inverts the green and blue channels of the frames: ::
+
+ def invert_green_blue(image):
+ return image[:,:,[0,2,1]]
+
+ modifiedClip = my_clip.fl_image( invert_green_blue )
+
+Finally, you may want to process the clip by taking into account both the time and the frame picture. This is possible with the method ``clip.fl(filter)``. The filter must be a function which takes two arguments and returns a picture. the fist argument is a ``get_frame`` method (i.e. a function ``g(t)`` which given a time returns the clip's frame at that time), and the second argument is the time. ::
+
+ def scroll(get_frame, t):
+ """
+ This function returns a 'region' of the current frame.
+ The position of this region depends on the time.
+ """
+ frame = get_frame(t)
+ frame_region = frame[int(t):int(t)+360,:]
+ return frame_region
+
+ modifiedClip = my_clip.fl( scroll )
+
+This will scroll down the clip, with a constant height of 360 pixels.
+
+When programming a new effect, whenever it is possible, prefer using ``fl_time`` and
+``fl_image`` instead of ``fl`` if possible when implementing
+new effects. The reason is that, when these effects are applied to
+ImageClips, MoviePy will recognize that these methods do not need to be applied to each frame, which will
+result in faster renderings.
diff --git a/docs/getting_started/efficient_moviepy.rst b/docs/getting_started/efficient_moviepy.rst
index e09d35ca..d6c090a2 100644
--- a/docs/getting_started/efficient_moviepy.rst
+++ b/docs/getting_started/efficient_moviepy.rst
@@ -1,19 +1,82 @@
+.. _efficient:
+
How to be efficient with MoviePy
================================
This section gathers tips and tricks to make the most of what is already known worldwide as *the MoviePy experience*.
-
-The best way to start with MoviePy is to use it with the IPython Notebook, as it has autocompletion which will help you find all you need and discover all the available methods.
+Let us first say that the best way to start with MoviePy is to use it with the IPython Notebook: it makes it easier to preview clips (as we will see in this section), has autocompletion, and can display the documentation for the different methods of the library.
Should I use ``moviepy.editor`` ?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Most examples in this documentation use the submodule ``moviepy.editor``, but this submodule is not adapted to all needs so should *you* use it ? Short answer: if you use MoviePy to edit videos *by hand*, use it, but if you use MoviePy inside a larger library or program or webserver, it is better to avoid it and just load the functions that you need.
+
+The module ``moviepy.editor`` can be loaded using one of the three following methods: ::
-Use the IPython Notebook !
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ from moviepy.editor import * # imports everything, quick and dirty
+ import moviepy.editor as mpy # Clean. Then use mpy.VideoClip, etc.
+ from moviepy.editor import VideoFileClip # just import what you need
+
+With any of these lines, the ``moviepy.editor`` module will actually do a lot of work behind the curtain: It will fetch all the most common classes, functions and subpackages of MoviePy, initialize a PyGame session (if PyGame is installed) to be able to preview video clips, and implement some shortcuts, like adding the ``resize`` transformation to the clips. This way you can use ``clip.resize(width=240)`` instead of the longer ``clip.fx( resize, width=240)``. In short, ``moviepy.editor``
+provides all you need to play around and edit your videos but it will take time to load (circa one second). So if all you need is one or two features inside another library, it is better to import directly what you need, as follows: ::
+
+ from moviepy.video.io.VideoFileClip import VideoFileClip
+ from moviepy.video.fx.resize import resize
The many ways of previewing a clip
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+When you are editing a video or trying to achieve an effect with MoviePy through a trial and error process, generating the video at each trial can be very long. This section presents a few tricks to go faster.
+
+clip.save_frame
+"""""""""""""""""
+
+Most of the time, just having one frame of the video can tell you if you are doing the right thing. You can save just one frame of the clip to a file as follows: ::
+
+ my_clip.save_frame("frame.jpeg") # saves the first frame
+ my_clip.save_frame("frame.png", t=2) # saves the frame a t=2s
+
+clip.show
+""""""""""
+
+The methods ``clip.show`` and ``clip.preview`` require to have PyGame installed. PyGame must also be initialized (it will always be the case if you use the ``moviepy.editor`` module)
+
+The method ``clip.show`` enables preview one frame of a clip without having to write it to a file: the following lines display the frame in a PyGame window ::
+
+ my_clip.show() # shows the first frame of the clip
+ my_clip.show(10.5) # shows the frame of the clip at t=10.5s
+ my_clip.show(10.5, interactive = True)
+
+The last line above displays the frame in an interactive way: if you click somewhere in the frame, it will print the position and color of the pixel. Press Escape to exit when you are done.
+
+
+clip.preview
+"""""""""""""
+
+A clip previewed is generated and displayed (in a PyGame window) at the same time. ::
+
+ my_clip.preview() # preview with default fps=15
+ my_clip.preview(fps=25)
+ my_clip.preview(fps=15, audio=False) # don't play sound.
+
+If you click somewhere in the frames when the clip is being previewed, it will print the position and color of the pixel clicked. Press Escape abort the previewing.
+
+Note that if the clip is complex and your computer not fast enough, the preview will appear slowed down compared to the real speed of the clip. In this case you can try to lower the frame rate (for instance to 10) or reduce the size of the clip with ``clip.resize``, it helps.
+
+ipython_display
+""""""""""""""""
+
+When using the IPython notebook
+
+.. image:: ../demo_preview.jpeg
+ :width: 500px
+ :align: center
+
+Note that ``ipython_display`` only works when it is the last command of the cell. You can provide any valid HTML5 options. For instance, when previewing a clip that you will turn into a gif, you need the preview to start automatically and to loop (i.e. replay indefinitely), so you will write ::
+
+ ipython_display(my_clip, autoplay=1, loop=1)
\ No newline at end of file
diff --git a/docs/getting_started/getting_started.rst b/docs/getting_started/getting_started.rst
index ac7a26c6..f8d171ce 100644
--- a/docs/getting_started/getting_started.rst
+++ b/docs/getting_started/getting_started.rst
@@ -2,6 +2,10 @@
These pages give you everything you need to start editing with MoviePy. Then the best way to learn is to have a look at the provided :ref:`examples` or the different ressources presented in the :ref:`gallery`.
+
+.. figure:: demo_preview.jpeg
+
+
Getting started with MoviePy
------------------------------
@@ -11,6 +15,7 @@ Getting started with MoviePy
quick_presentation
clips
+ compositing
effects
advanced_tools
efficient_moviepy
\ No newline at end of file
diff --git a/docs/advanced_uses/ipynb_example.jpeg b/docs/getting_started/ipynb_example.jpeg
similarity index 100%
rename from docs/advanced_uses/ipynb_example.jpeg
rename to docs/getting_started/ipynb_example.jpeg
diff --git a/docs/getting_started/quick_presentation.rst b/docs/getting_started/quick_presentation.rst
index 5b91cee3..9621b7ac 100644
--- a/docs/getting_started/quick_presentation.rst
+++ b/docs/getting_started/quick_presentation.rst
@@ -1,7 +1,9 @@
+.. _quick_presentation:
+
Quick presentation
===================
-This section explains when MoviePy can be used, how it can be used, and how it works.
+This section explains when MoviePy can be used and how it works.
Do I need MoviePy ?
~~~~~~~~~~~~~~~~~~~
@@ -14,19 +16,22 @@ There are already many good free video editing softwares out there with nice gra
- You want to code your own video effects to do something no existing video editor can.
- You want to create animations from images generated by another python library (Matplotlib, Mayavi, Gizeh...)
+Advantages and limitations
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
MoviePy has been developed with the following goals in mind:
- **Simple an intuitive**. Basic operations can be done in one line. The code is easy to learn and easy to understand for newcomers.
- **Flexible**. You have total control over the frames of the video and audio, and creating your own effects is easy as Py.
- **Portable**. The code uses very common software (Numpy and FFMPEG) and can run on (almost) any machine with (almost) any version of Python.
-Now for the limitations: MoviePy cannot stream videos (read from a webcam, or render a video live on a distant machine), it cannot do 3D effects (by lack of a nice 3D library for Python) and is not well designed for video processing involving successive frames of a movie (like video stabilization, you'll need another software for that). Also, if you only need to do frame-by-frame video analysis (with face detection or other fancy stuff) you may want to use the libraries OpenCV and SimpleCV instead.
+Now for the limitations: for now MoviePy cannot stream videos (read from a webcam, or render a video live on a distant machine), it cannot do 3D effects (by lack of a nice 3D library for Python) and is not really designed for video processing involving many successive frames of a movie (like video stabilization, you'll need another software for that). Also, if you only need to do frame-by-frame video analysis (with face detection or other fancy stuff) you may want to use the libraries OpenCV and SimpleCV instead.
Example code
~~~~~~~~~~~~~~
-In a typical MoviePy script, you load some video or audio files, modify them, put them together, and write the result to a new video file. As an example, let us load a video of my last holidays, lower the volume, add a title in the center of the video for the first ten seconds, and write the result in a file: ::
+In a typical MoviePy script, you load video or audio files, modify them, put them together, and write the final result to a new video file. As an example, let us load a video of my last holidays, lower the volume, add a title in the center of the video for the first ten seconds, and write the result in a file: ::
# Import everything needed to edit video clips
from moviepy.editor import *
@@ -53,7 +58,7 @@ In a typical MoviePy script, you load some video or audio files, modify them, pu
How MoviePy works
~~~~~~~~~~~~~~~~~~~
-MoviePy uses the software ``ffmpeg`` to read and to export video and audio files. It also (optionally) uses ImageMagick to generate texts and write GIF files. The processing of the different media is ensured by Python's fast numerical library Numpy, and advanced effects and enhancements can be done using some of Python's numerous image processing library (PIL, Scikit-image, scipy, etc.).
+MoviePy uses the software ``ffmpeg`` to read and to export video and audio files. It also (optionally) uses ImageMagick to generate texts and write GIF files. The processing of the different media is ensured by Python's fast numerical library Numpy. Advanced effects and enhancements use some of Python's numerous image processing libraries (PIL, Scikit-image, scipy, etc.).
.. image:: explanations.jpeg
:width: 570px
@@ -62,11 +67,11 @@ MoviePy uses the software ``ffmpeg`` to read and to export video and audio files
Basic concepts
~~~~~~~~~~~~~~~
-The central objects of MoviePy are *clips*, which can be ``AudioClips`` or ``VideoClips``. They can be modified (cut, slowed down, darkened...) or put mixed with clips to form new clips, they can be previewed (using either PyGame or the IPython Notebook) and rendered to a file (as a MP4, a GIF, a MP3, etc.). ``VideoClips`` for instance can be created from a video file, an image, a text, or a custom animation. They can have an audio track (which is an ``AudioClip``) and a mask (a special ``VideoClip`` indicating which parts of the clip to hide when the clip is mixed with other clips). See :ref:`clips` for more details.
+The central objects of MoviePy are *clips*, which can be ``AudioClips`` or ``VideoClips``. They can be modified (cut, slowed down, darkened...) or put mixed with clips to form new clips, they can be previewed (using either PyGame or the IPython Notebook) and rendered to a file (as a MP4, a GIF, a MP3, etc.). ``VideoClips`` for instance can be created from a video file, an image, a text, or a custom animation. They can have an audio track (which is an ``AudioClip``) and a mask (a special ``VideoClip`` indicating which parts of the clip to hide when the clip is mixed with other clips). See :ref:`clips` and :ref:`CompositeVideoClips` for more details.
A clip can be modified using one of moviepy's numerous effects (like in ``clip.resize(width="360")``, ``clip.subclip(t1,t2)``, or ``clip.fx(vfx.black_white)``) or using a user-implemented effect. MoviePy implements many functions (like ``clip.fl``, ``clip.fx``, etc.) which make it very easy to code your own effect in a few lines. See :ref:`effects` for more.
-You will also find a few advanced goodies in ``moviepy.video.tools`` to track objects in a video, draw simple shapes and color gradients (very useful for masks), generate subtitles and end credits, etc. See :ref:`advanced_tools` for a description of these.
+You will also find a few advanced goodies in ``moviepy.video.tools`` to track objects in a video, draw simple shapes and color gradients (very useful for masks), generate subtitles and end credits, etc. See :ref:`advancedtools` for a description of these.
Finally, although MoviePy has no graphical user interface, there are many ways to preview a clip which allow you to fine-tune your scripts and be sure that everything is perfect when you render you video in high quality. See :ref:`efficient`.
diff --git a/docs/getting_started/stacked.jpeg b/docs/getting_started/stacked.jpeg
new file mode 100644
index 00000000..7be3748a
Binary files /dev/null and b/docs/getting_started/stacked.jpeg differ
diff --git a/docs/index.rst b/docs/index.rst
index d30b8166..b15b4063 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -8,7 +8,13 @@
-MoviePy is a Python module for script-based video editing. It enables basic operations (cuts, concatenations, title insertions) to be done in a few lines, and can be used for video compositing (a.k.a. non-linear editing), video processing, or to create advanced effects. It can read and write all the most common video formats, including GIF.
+MoviePy is a Python module for video editing, which can be used for basic operations (like cuts, concatenations, title insertions), video compositing (a.k.a. non-linear editing), video processing, or to create advanced effects. It can read and write the most common video formats, including GIF.
+
+Here it is in action (run in an IPython Notebook):
+
+.. image:: demo_preview.jpeg
+ :width: 500px
+ :align: center
User Guide
------------
@@ -22,6 +28,9 @@ User Guide
examples/examples
FAQ
ref/ref
+
+Contribute !
+--------------
MoviePy is an open source software originally written by Zulko_ and released under the MIT licence. It works on Windows, Mac, and Linux, with Python 2 or Python 3. The code is hosted on Github_, where you can push improvements, report bugs and ask for help. There is also a MoviePy forum on Reddit_ and a mailing list on librelist_ .
@@ -37,7 +46,6 @@ MoviePy is an open source software originally written by Zulko_ and released und
<iframe src="http://ghbtns.com/github-btn.html?user=Zulko&repo=moviepy&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="152px" height="30px"></iframe>
-
.. <a href="https://github.com/Zulko/moviepy">
.. <img style="position: absolute; top: 0; right: 0; border: 0;"
.. src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"
diff --git a/docs/install.rst b/docs/install.rst
index d8e6feff..c7b258a3 100644
--- a/docs/install.rst
+++ b/docs/install.rst
@@ -1,3 +1,5 @@
+.. _install:
+
Download and Installation
==========================
@@ -44,7 +46,7 @@ For advanced image processing you will need one or several of these packages. fo
- The Python Imaging Library (PIL) or, better, its branch Pillow_ .
- Scipy_ (for tracking, segmenting, etc.), and can be used for resizing video clips if PIL and OpenCV aren't installed on your computer.
- `Scikit Image`_ may be needed for some advanced image manipulation.
-- `OpenCV 2.4.6`_ (provides the package ``cv2``) or more recent may be needed for some advanced image manipulation. See :ref:`opencv`
+- `OpenCV 2.4.6`_ (provides the package ``cv2``) or more recent may be needed for some advanced image manipulation. See :ref:`opencv`.
If you are on linux, these softwares will surely be in your repos.
diff --git a/docs/ref/code_origanization.rst b/docs/ref/code_origanization.rst
index 502e6635..6c031127 100644
--- a/docs/ref/code_origanization.rst
+++ b/docs/ref/code_origanization.rst
@@ -1,3 +1,5 @@
+.. _codeorganization:
+
Organization of MoviePy's code
===============================
@@ -18,7 +20,4 @@ The submodules ``moviepy.audio`` and ``moviepy.video`` are organized approximate
- ``io`` contains everything required to read files, write files, preview the clip or use a graphical interface of any sort. It contains the objects that speak to FFMEG and ImageMagick, the classes AudioFileClip and VideoFileClip, the functions used to preview a clip with pygame or to embed a video in HTML5 (for instance in the IPython Notebook).
- ``fx`` contains a collection of effects and filters (like turning a video black and white, correcting luminosity, zooming or creating a scrolling effect). To add an effect to MoviePy, you simply add a new file ``my_effect.py`` to this folder, and in the file you define the function ``my_effect(clip, *other_parameters)``.
- ``compositing`` contains functions and classes to compose videoclips (CompositeVideoClip, concatenate, clips_array)
-- ``tools`` contains advanced tools that are not effects but can help edit clips or generate new clips (tracking, subtitles, etc.)
-
-
-The Clip object and some basic methods
\ No newline at end of file
+- ``tools`` contains advanced tools that are not effects but can help edit clips or generate new clips (tracking, subtitles, etc.)
\ No newline at end of file
diff --git a/docs/ref/ref.rst b/docs/ref/ref.rst
index 32a372eb..ef205053 100644
--- a/docs/ref/ref.rst
+++ b/docs/ref/ref.rst
@@ -5,7 +5,7 @@ Reference Manual
================
The documentation may be a little messy for the moment, it will get better with time.
-If you want to hack into the code, read :ref:`code_organization`.
+If you want to hack into the code or locate a particular function, read :ref:`codeorganization` .
.. toctree::
diff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.py
index 6c54724d..c6274fab 100644
--- a/moviepy/audio/AudioClip.py
+++ b/moviepy/audio/AudioClip.py
@@ -6,7 +6,7 @@ from moviepy.tools import (deprecated_version_of,
extensions_dict)
from moviepy.Clip import Clip
-
+from tqdm import tqdm
class AudioClip(Clip):
""" Base class for audio clips.
@@ -54,9 +54,39 @@ class AudioClip(Clip):
if duration is not None:
self.duration = duration
self.end = duration
+
+ @requires_duration
+ def iter_chunks(self, chunksize=None, chunk_duration=None, fps=None,
+ quantize=False, nbytes=2, progress_bar=False):
+ """ Iterator that returns the whole sound array of the clip by chunks
+ """
+ if fps is None:
+ fps=self.fps
+ if chunk_duration is not None:
+ chunksize = int(chunk_duration*fps)
+
+ totalsize = int(fps*self.duration)
+
+ if (totalsize % chunksize == 0):
+ nchunks = totalsize // chunksize
+ else:
+ nchunks = totalsize // chunksize + 1
+
+ pospos = list(range(0, totalsize, chunksize))+[totalsize]
+
+ def generator():
+ for i in range(nchunks):
+ tt = (1.0/fps)*np.arange(pospos[i],pospos[i+1])
+ yield self.to_soundarray(tt, nbytes= nbytes, quantize=quantize, fps=fps,
+ buffersize=chunksize)
+
+ if progress_bar:
+ return tqdm(generator(), total=nchunks)
+ else:
+ return generator()
@requires_duration
- def to_soundarray(self,tt=None,fps=None, nbytes=2):
+ def to_soundarray(self,tt=None, fps=None, quantize=False, nbytes=2, buffersize=50000):
"""
Transforms the sound into an array that can be played by pygame
or written in a wav file. See ``AudioClip.preview``.
@@ -73,18 +103,47 @@ class AudioClip(Clip):
2 for 16bit, 4 for 32bit sound.
"""
- if tt is None:
- tt = np.arange(0,self.duration, 1.0/fps)
-
+ if fps is None:
+ fps = self.fps
+
+ stacker = np.vstack if self.nchannels==2 else np.hstack
+ max_duration = 1.0 * buffersize / fps
+ if (tt is None):
+ if self.duration>max_duration:
+ return stacker(self.iter_chunks(fps=fps, quantize=quantize, nbytes=2,
+ chunksize=buffersize))
+ else:
+ tt = np.arange(0,clip.duration, 1.0/fps)
+ """
+ elif len(tt)> 1.5*buffersize:
+ nchunks = int(len(tt)/buffersize+1)
+ tt_chunks = np.array_split(tt, nchunks)
+ return stacker([self.to_soundarray(tt=ttc, buffersize=buffersize, fps=fps,
+ quantize=quantize, nbytes=nbytes)
+ for ttc in tt_chunks])
+ """
#print tt.max() - tt.min(), tt.min(), tt.max()
snd_array = self.get_frame(tt)
- snd_array = np.maximum(-0.99,
- np.minimum(0.99,snd_array))
- inttype = {1:'int8',2:'int16', 4:'int32'}[nbytes]
- return (2**(8*nbytes-1)*snd_array).astype(inttype)
-
-
+
+ if quantize:
+ snd_array = np.maximum(-0.99, np.minimum(0.99,snd_array))
+ inttype = {1:'int8',2:'int16', 4:'int32'}[nbytes]
+ snd_array= (2**(8*nbytes-1)*snd_array).astype(inttype)
+
+ return snd_array
+
+ def max_volume(self, stereo=False, chunksize=50000, progress_bar=False):
+
+ stereo = stereo and (self.nchannels == 2)
+
+ maxi = np.array([0,0]) if stereo else 0
+ for chunk in self.iter_chunks(chunksize=chunksize, progress_bar=progress_bar):
+ maxi = np.maximum(maxi,abs(chunk).max(axis=0)) if stereo else max(maxi,abs(chunk).max())
+ return maxi
+
+
+
@requires_duration
def write_audiofile(self,filename, fps=44100, nbytes=2,
@@ -238,7 +297,7 @@ class CompositeAudioClip(AudioClip):
self.make_frame = make_frame
-def concatenate_audio(clips):
+def concatenate_audioclips(clips):
durations = [c.duration for c in clips]
tt = np.cumsum([0]+durations) # start times, and end time.
newclips= [c.set_start(t) for c,t in zip(clips, tt)]
diff --git a/moviepy/audio/fx/audio_loop.py b/moviepy/audio/fx/audio_loop.py
index 524e641b..43c967f8 100644
--- a/moviepy/audio/fx/audio_loop.py
+++ b/moviepy/audio/fx/audio_loop.py
@@ -1,4 +1,4 @@
-from ..AudioClip import concatenate_audio
+from ..AudioClip import concatenate_audioclips
def audio_loop(audioclip, nloops=None, duration=None):
""" Loops over an audio clip.
@@ -20,9 +20,9 @@ def audio_loop(audioclip, nloops=None, duration=None):
if duration is not None:
nloops = int( duration/ audioclip.duration)+1
- return concatenate_audio(nloops*[audioclip]).set_duration(duration)
+ return concatenate_audioclips(nloops*[audioclip]).set_duration(duration)
else:
- return concatenate_audio(nloops*[audioclip])
+ return concatenate_audioclips(nloops*[audioclip])
diff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.py
index 604dff72..8227be62 100644
--- a/moviepy/audio/io/ffmpeg_audiowriter.py
+++ b/moviepy/audio/io/ffmpeg_audiowriter.py
@@ -151,6 +151,14 @@ def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
codec=codec, bitrate=bitrate,
logfile=logfile)
+
+
+ for chunk in clip.iter_chunks(chunksize=buffersize,
+ progress_bar=True, quantize=True,
+ nbytes= nbytes, fps=fps):
+ writer.write_frames(chunk)
+
+ """
totalsize = int(fps*clip.duration)
if (totalsize % buffersize == 0):
@@ -159,12 +167,11 @@ def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
nchunks = totalsize // buffersize + 1
pospos = list(range(0, totalsize, buffersize))+[totalsize]
-
for i in tqdm(range(nchunks)):
tt = (1.0/fps)*np.arange(pospos[i],pospos[i+1])
sndarray = clip.to_soundarray(tt, nbytes= nbytes)
writer.write_frames(sndarray)
-
+ """
writer.close()
diff --git a/moviepy/decorators.py b/moviepy/decorators.py
index 1a120abf..0224b8bf 100644
--- a/moviepy/decorators.py
+++ b/moviepy/decorators.py
@@ -14,7 +14,11 @@ def outplace(f, clip, *a, **k):
f(newclip, *a, **k)
return newclip
-
+def convert_masks_to_RGB(f, clip, *a, **k):
+ if clip.ismask:
+ clip = clip.to_RGB()
+ return f(clip, *a, **k)
@decorator.decorator
def apply_to_mask(f, clip, *a, **k):
diff --git a/moviepy/editor.py b/moviepy/editor.py
index 533bc988..9260d73a 100644
--- a/moviepy/editor.py
+++ b/moviepy/editor.py
@@ -23,9 +23,9 @@ from .video.io.VideoFileClip import VideoFileClip
from .video.io.ImageSequenceClip import ImageSequenceClip
from .video.VideoClip import VideoClip, ImageClip, ColorClip, TextClip
from .video.compositing.CompositeVideoClip import CompositeVideoClip, clips_array
-from .video.compositing.concatenate import concatenate
+from .video.compositing.concatenate import concatenate_videoclips, concatenate # concatenate=deprecated
-from .audio.AudioClip import AudioClip, CompositeAudioClip, concatenate_audio
+from .audio.AudioClip import AudioClip, CompositeAudioClip, concatenate_audioclips
from .audio.io.AudioFileClip import AudioFileClip
# FX
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index 6bf433d8..a2df29f5 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -33,7 +33,8 @@ from ..decorators import (apply_to_mask,
requires_duration,
outplace,
add_mask_if_none,
- convert_to_seconds)
+ convert_to_seconds,
+ convert_masks_to_RGB)
import os
try:
@@ -118,6 +119,7 @@ class VideoClip(Clip):
@convert_to_seconds(['t'])
+ @convert_masks_to_RGB
def save_frame(self, filename, t=0, savemask=False):
""" Save a clip's frame to an image file.
@@ -129,6 +131,7 @@ class VideoClip(Clip):
the alpha layer of the picture.
"""
+
im = self.get_frame(t)
if savemask and self.mask is not None:
mask = 255 * self.mask.get_frame(t)
@@ -137,6 +140,7 @@ class VideoClip(Clip):
@requires_duration
+ @convert_masks_to_RGB
def write_videofile(self, filename, fps=24, codec=None,
bitrate=None, audio=True, audio_fps=44100,
preset="medium",
@@ -330,6 +334,7 @@ class VideoClip(Clip):
@requires_duration
+ @convert_masks_to_RGB
def write_images_sequence(self, nameformat, fps=None, verbose=True):
""" Writes the videoclip to a sequence of image files.
@@ -433,7 +438,7 @@ class VideoClip(Clip):
>>> myClip.speedx(0.5).to_gif('myClip.gif')
"""
-
+
if tempfiles:
write_gif_with_tempfiles(self, filename, fps=fps,
program=program, opt=opt, fuzz=fuzz,
diff --git a/moviepy/video/compositing/concatenate.py b/moviepy/video/compositing/concatenate.py
index 9f97d315..df753eba 100644
--- a/moviepy/video/compositing/concatenate.py
+++ b/moviepy/video/compositing/concatenate.py
@@ -1,13 +1,14 @@
import numpy as np
+from moviepy.tools import deprecated_version_of
from moviepy.video.VideoClip import VideoClip
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
from moviepy.audio.AudioClip import CompositeAudioClip
from moviepy.video.compositing.on_color import on_color
-def concatenate(clipslist, method="chain", transition=None, bg_color=(0, 0, 0),
- transparent=False, ismask=False, padding = 0):
+def concatenate_videoclips(clipslist, method="chain", transition=None, bg_color=(0, 0, 0),
+ transparent=False, ismask=False, padding = 0):
""" Concatenates several video clips
Returns a video clip made by clip by concatenating several video clips.
@@ -102,3 +103,6 @@ def concatenate(clipslist, method="chain", transition=None, bg_color=(0, 0, 0),
result.audio = CompositeAudioClip([a.set_start(t)
for a,t in audio_t])
return result
+
+
+concatenate = deprecated_version_of(concatenate_videoclips, "concatenate_videoclips")
\ No newline at end of file
diff --git a/moviepy/video/io/preview.py b/moviepy/video/io/preview.py
index b0d6dd59..2796c9fb 100644
--- a/moviepy/video/io/preview.py
+++ b/moviepy/video/io/preview.py
@@ -4,7 +4,7 @@ import time
import pygame as pg
import numpy as np
-from moviepy.decorators import requires_duration
+from moviepy.decorators import (requires_duration, convert_masks_to_RGB)
from moviepy.tools import cvsecs
@@ -20,6 +20,7 @@ def imdisplay(imarray, screen=None):
pg.display.flip()
+@convert_masks_to_RGB
def show(clip, t=0, with_mask=True, interactive=False):
"""
Splashes the frame of clip corresponding to time ``t``.
@@ -39,8 +40,6 @@ def show(clip, t=0, with_mask=True, interactive=False):
if isinstance(t, tuple):
t = cvsecs(*t)
- if clip.ismask:
- clip = clip.to_RGB()
if with_mask and (clip.mask != None):
import moviepy.video.compositing.CompositeVideoClip as cvc
clip = cvc.CompositeVideoClip([clip.set_pos((0,0))])
@@ -64,6 +63,7 @@ def show(clip, t=0, with_mask=True, interactive=False):
time.sleep(.03)
@requires_duration
+@convert_masks_to_RGB
def preview(clip, fps=15, audio=True, audio_fps=22050,
audio_buffersize=3000, audio_nbytes=2):
"""
@@ -90,9 +90,6 @@ def preview(clip, fps=15, audio=True, audio_fps=22050,
import pygame as pg
- if clip.ismask:
- clip = clip.to_RGB()
-
# compute and splash the first image
screen = pg.display.set_mode(clip.size)