Video editing with Python
ensured utf8 video frames for export
Zulkoaeaf2ca7e564
diff --git a/docs/getting_started/effects.rst b/docs/getting_started/effects.rstindex cc5db928..ab23c173 100644--- a/docs/getting_started/effects.rst+++ b/docs/getting_started/effects.rst@@ -6,7 +6,7 @@ Clips transformations and effectsThere are several categories of clip modifications in MoviePy:- The very common methods to change the attributes of a clip: ``clip.set_duration``, ``clip.set_audio``, ``clip.set_mask``, ``clip.set_start`` etc.-- The already-implemented effects. Core effects like ``clip.subclip(t1, t2)`` (keep only the cut between t1 and t2), which are very important, are implemented as class methods. More advanced and less common effects like ``loop`` (makes the clip play in a loop) or ``time_mirror`` (makes the clip play backwards) are placed in the special modules ``moviepy.video.fx`` and ``moviepy.audio.fx``.+- The already-implemented effects. Core effects like ``clip.subclip(t1, t2)`` (keep only the cut between t1 and t2), which are very important, are implemented as class methods. More advanced and less common effects like ``loop`` (makes the clip play in a loop) or ``time_mirror`` (makes the clip play backwards) are placed in the special modules ``moviepy.video.fx`` and ``moviepy.audio.fx`` and are applied with the ``clip.fx`` method, for instance ``clip.fx(time_mirror)`` (makes the clip play backwards), ``clip.fx(black_white)`` (turns the clip black and white), etc.- The effects that you can create yourself. usingImportantly, all these effects have in common that they are **not inplace**: none of these effects modifies the original clip, they all create a new clip that is a version of the former with the changes applied. For instance: ::@@ -15,13 +15,7 @@ Importantly, all these effects have in common that they are **not inplace**: nonmy_clip.set_start(t=5) # does nothing, changes nothing !my_new_clip = my_clip.set_duration(t=5) # good !--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.-+Also, when you apply an effect like ``clip.resize(width=640)``, only the first frame of the clip is computed, all the other frames will be computed only when they are required (so when you write the clip to a file of when you preview it). Said otherwise, creating a new clip is neither time nor memory hungry, it's at the final rendering that all the computations happen.Time representations in MoviePy---------------------------------@@ -37,7 +31,7 @@ Methods to change the clip attributesAlready-implemented effects-------------------------------See :ref:`ref_videofx` for a complete list and documentation of these+See :ref:`refvideofx` for a complete list and documentation of theseMethods to create custom effectsdiff --git a/docs/index.rst b/docs/index.rstindex b15b4063..eb889aca 100644--- a/docs/index.rst+++ b/docs/index.rst@@ -37,7 +37,7 @@ MoviePy is an open source software originally written by Zulko_ and released und.. raw:: html<a href="https://twitter.com/share" class="twitter-share-button"- data-text="MoviePy, script-based video editing" data-size="large" data-hashtags="MoviePy">Tweet+ data-text="MoviePy - Video editing with Python" data-size="large" data-hashtags="MoviePy">Tweet</a><script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';diff --git a/docs/ref/videofx.rst b/docs/ref/videofx.rstindex 81ab7d19..f0da7fa2 100644--- a/docs/ref/videofx.rst+++ b/docs/ref/videofx.rst@@ -1,4 +1,4 @@-.. _ref_videofx:+.. _refvideofx:***********************moviepy.video.fx (vfx)@@ -6,7 +6,9 @@ moviepy.video.fx (vfx)The module ``moviepy.video.fx`` regroups functions meant to be used with ``videoclip.fx()``.Because this module is starting to be large and will be larger in the future, it allows two kinds of import.-You can either import a single function like this: ::+You can either im+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.+port a single function like this: ::from moviepy.video.fx.scroll import cropnewclip = myclip.fx( vfx.crop, x1=15)diff --git a/moviepy/Clip.py b/moviepy/Clip.pyindex 9ee99d41..4d9393cb 100644--- a/moviepy/Clip.py+++ b/moviepy/Clip.py@@ -390,7 +390,8 @@ class Clip:return newclip@requires_duration- def iter_frames(self, fps=None, with_times = False, progress_bar=False):+ def iter_frames(self, fps=None, with_times = False, progress_bar=False,+ dtype=None):""" Iterates over all the frames of the clip.Returns each frame of the clip as a HxWxN np.array,@@ -402,6 +403,8 @@ class Clip:The ``fps`` (frames per second) parameter is optional if theclip already has a ``fps`` attribute.++ Use dtype="uint8" when using the pictures to write video, images...Examples---------@@ -419,10 +422,14 @@ class Clip:def generator():for t in np.arange(0, self.duration, 1.0/fps):+ frame = self.get_frame(t)+ if (dtype is not None) and (frame.dtype != dtype):+ frame = frame.astype(dtype)+if with_times:- yield t, self.get_frame(t)+ yield t, frameelse:- yield self.get_frame(t)+ yield frameif progress_bar:nframes = int(self.duration*fps)+1diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex 12f44d5c..a0853994 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -120,22 +120,26 @@ class VideoClip(Clip):@convert_to_seconds(['t'])@convert_masks_to_RGB- def save_frame(self, filename, t=0, savemask=False):+ def save_frame(self, filename, t=0, withmask=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'.- If ``savemask`` is ``True`` the mask is saved in- the alpha layer of the picture.+ If ``withmask`` is ``True`` the mask is saved in+ the alpha layer of the picture (only works with PNGs)."""im = self.get_frame(t)- if savemask and self.mask is not None:+ if im.dtype != "uint8":+ im = im.astype("uint8")++ if withmask and self.mask is not None:mask = 255 * self.mask.get_frame(t)im = np.dstack([im, mask]).astype('uint8')+ffmpeg_write_image(filename, im)@@ -335,7 +339,8 @@ class VideoClip(Clip):@requires_duration@convert_masks_to_RGB- def write_images_sequence(self, nameformat, fps=None, verbose=True):+ def write_images_sequence(self, nameformat, fps=None, verbose=True,+ withmask=True):""" Writes the videoclip to a sequence of image files.@@ -353,6 +358,9 @@ class VideoClip(Clip):clip. If not specified, the clip's ``fps`` attribute willbe used if it has one.+ withmask+ will save the clip's mask (if any) as an alpha canal (PNGs only)+verboseVerbose output ?@@ -383,7 +391,7 @@ class VideoClip(Clip):for i, t in tqdm(enumerate(tt), total=total):name = nameformat % (i + 1)filenames.append(name)- self.save_frame(name, t, savemask=True)+ self.save_frame(name, t, withmask=withmask)verbose_print(verbose,"MoviePy: Done writing frames %s." % (nameformat))@@ -667,7 +675,7 @@ class VideoClip(Clip):@apply_to_mask@outplace- def set_pos(self, pos, relative=False):+ def set_position(self, pos, relative=False):""" Set the clip's position in compositions.Sets the position that the clip will have when included@@ -902,6 +910,8 @@ class ImageClip(VideoClip):# The old functions to_videofile, to_gif, to_images sequences have been# replaced by the more explicite write_videofile, write_gif, etc.+VideoClip.set_pos = deprecated_version_of(VideoClip.set_position,+ 'set_pos')VideoClip.to_videofile = deprecated_version_of(VideoClip.write_videofile,'to_videofile')VideoClip.to_gif = deprecated_version_of(VideoClip.write_gif, 'to_gif')diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.pyindex 23d05ef7..28a4ab4b 100644--- a/moviepy/video/compositing/CompositeVideoClip.py+++ b/moviepy/video/compositing/CompositeVideoClip.py@@ -121,7 +121,7 @@ def clips_array(array, rows_widths=None, cols_widths=None,bg_color = bg_color).set_duration(clip.duration))- array[i,j] = clip.set_pos((x,y))+ array[i,j] = clip.set_pos((x,y))return CompositeVideoClip(array.flatten(), size = (xx[-1],yy[-1]),transparent=transparent,diff --git a/moviepy/video/fx/loop.py b/moviepy/video/fx/loop.pyindex 50d7a653..ab9f7748 100644--- a/moviepy/video/fx/loop.py+++ b/moviepy/video/fx/loop.py@@ -24,5 +24,5 @@ def loop(self, n=None, duration=None):if n:duration = n*self.durationif duration:- result.duration = duration+ result = result.set_duration(duration)return resultdiff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.pyindex 536a5a08..a7a1c399 100644--- a/moviepy/video/io/ffmpeg_writer.py+++ b/moviepy/video/io/ffmpeg_writer.py@@ -15,7 +15,6 @@ except ImportError:from moviepy.config import get_settingfrom moviepy.tools import verbose_print-class FFMPEG_VideoWriter:""" A class for FFMPEG-based video writing.@@ -200,12 +199,14 @@ def ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,nframes = int(clip.duration*fps)for t,frame in clip.iter_frames(progress_bar=True, with_times=True,- fps=fps):+ fps=fps, dtype="uint8"):if withmask:- mask = 255*clip.mask.get_frame(t)+ mask = (255*clip.mask.get_frame(t))+ if mask.dtype != "uint8":+ mask = mask.astype("uint8")frame = np.dstack([frame,mask])-- writer.write_frame(frame.astype("uint8"))++ writer.write_frame(frame)writer.close()@@ -218,6 +219,9 @@ def ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,def ffmpeg_write_image(filename, image, logfile=False):""" Writes an image (HxWx3 or HxWx4 numpy array) to a file, usingffmpeg. """++ if image.dtype != 'uint8':+ image = image.astype("uint8")cmd = [ get_setting("FFMPEG_BINARY"), '-y','-s', "%dx%d"%(image.shape[:2][::-1]),@@ -238,12 +242,12 @@ def ffmpeg_write_image(filename, image, logfile=False):popen_params["creationflags"] = 0x08000000proc = sp.Popen(cmd, **popen_params)- proc.communicate(image.tostring())+ out, err = proc.communicate(image.tostring())if proc.returncode:err = "\n".join(["MoviePy running : %s" % cmd,"WARNING: this command returned an error:",- proc.stderr.read().decode('utf8')])+ err.decode('utf8')])raise IOError(err)del procdiff --git a/moviepy/video/io/html_tools.py b/moviepy/video/io/html_tools.pyindex afd60fb6..67f55100 100644--- a/moviepy/video/io/html_tools.py+++ b/moviepy/video/io/html_tools.py@@ -13,6 +13,9 @@ import osfrom base64 import b64encodefrom moviepy.tools import extensions_dict+from ..VideoClip import VideoClip, ImageClip+from moviepy.audio.AudioClip import AudioClip+try:from IPython.display import HTMLipython_available = True@@ -75,25 +78,24 @@ def html_embed(clip, filetype=None, maxduration=60, rd_kwargs=None,if rd_kwargs is None:rd_kwargs = {}- # QUICK AND VERY DIRTY: next step is use "isinstance" with classes.- # But cross-dependencies in modules may make it difficult...+if "Clip" in str(clip.__class__):TEMP_PREFIX = "__temp__"- if "ImageClip" in str(clip.__class__):+ if isinstance(clip,ImageClip):filename = TEMP_PREFIX+".png"- kwargs = {'filename':filename}+ kwargs = {'filename':filename, 'withmask':True}kwargs.update(rd_kwargs)clip.save_frame(**kwargs)- elif "Video" in str(clip.__class__):+ elif isinstance(clip,VideoClip):filename = TEMP_PREFIX+".mp4"kwargs = {'filename':filename, 'verbose':False, 'preset':'ultrafast'}kwargs.update(rd_kwargs)clip.write_videofile(**kwargs)- elif "AudioClip" in str(clip.__class__):+ elif isinstance(clip,AudioClip):filename = TEMP_PREFIX+".mp3"kwargs = {'filename': filename, 'verbose':False}kwargs.update(rd_kwargs)- clip.write_audiofile(filename, **kwargs)+ clip.write_audiofile(**kwargs)else:raise ValueError("Unknown class for the clip. Cannot embed and preview.")diff --git a/moviepy/video/tools/cuts.py b/moviepy/video/tools/cuts.pyindex 7bd23c51..d364fa71 100644--- a/moviepy/video/tools/cuts.py+++ b/moviepy/video/tools/cuts.py@@ -4,7 +4,7 @@ the cuts in MoviePy """import numpy as np-def find_period(clip,fps=None,tmin=.3):+def find_video_period(clip,fps=None,tmin=.3):if fps is None:fps=clip.fpsframe = lambda t: clip.get_frame(t).flatten()