Video editing with Python
fixed quality/fps in write_gif2. added __str__ in subtitles
Zulko85ec6f3e7657
diff --git a/README.rst b/README.rstindex 5d1045c9..28325d23 100644--- a/README.rst+++ b/README.rst@@ -25,42 +25,67 @@ A typical MoviePy script looks like that: ::MoviePy is an open-source software originally written by Zulko_ and released under the MIT licence.-The project is hosted on Github_ , where everyone is welcome to contribute and give feedback.+The project is hosted on Github_ , where everyone is welcome to contribute, ask for help or simply give feedback.-Download and Installation-----------------------------MoviePy requires the Python modules Numpy_, Decorator_, and tqdm_. All of these will all be automatically installed during MoviePy's installation.+Installation+---------------You will also need a **recent version** of the software ffmpeg_ , preferably downloaded directly from the ffmpeg website.--If you intend to use advanced features you must install a few other dependencies like ImageMagick_ , Pygame_ etc. (see `the docs <http://zulko.github.io/moviepy/install.html>`_).--First installation method : if you have ``pip`` installed, just type this in a terminal (sudo is optional on some systems) ::+**Method with pip:** if you have ``pip`` installed, just type this in a terminal (sudo is optional on some systems) ::(sudo) pip install moviepy-Second method : by hand. Download the sources, either on PyPI_ or (if you want the development version) on Github_, unzip everything in one folder, open a terminal and type ::+**Method by hand:** download the sources, either on PyPI_ or (if you want the development version) on Github_, unzip everything in one folder, open a terminal and type ::(sudo) python setup.py install++MoviePy depends on the Python modules Numpy_, Decorator_, and tqdm_, which will be automatically installed during MoviePy's installation.+Linking to ffmpeg~~~~~~~~~~~~~~~~~~-If you put have a ffmpeg binary in you executable folder (on Linux it will be ``/usr/bin``) it will be detected automatically by MoviePy. Else make sure that MoviePy can locate ffmpeg on your computer by running the script ``moviepy/conf.py`` that is in the sources. It it fails, then you must enter the path to the FFMPEG executable in the first line of this file ::+MoviePy requires a **recent version** of the software ffmpeg_ preferably downloaded **directly from the ffmpeg website**.++**Installed ffmpeg:** when you have installed ffmpeg, or (for linux users) when you have a ffmpeg binary in the ``/usr/bin`` folder, it will be detected automatically by MoviePy.++**Non-installed ffmpeg:** you can also simply place the ffmpeg binary somewhere on your computer and specify its path in the file `moviepy/conf.py` before installing MoviePy by hand.++Linking to ImageMagick+~~~~~~~~~~~~~~~~~~~~~~~~++ImageMagick_ is not strictly required, but some important features of MoviePy, like the creation of texts or animated GIFs, depend on it.++Once you have installed it, ImageMagick will be automatically detected by MoviePy, **except on Windows !**. Windows user, before installing MoviePy by hand, go into the ``moviepy/conf.py`` file and provide the path to the ImageMagick binary called `convert`. It should look like this ::- FFMPEG_BINARY = path/to/your/ffmpeg+ IMAGEMAGICK_BINARY = "C:\\Program Files\\ImageMagick_VERSION\\convert.exe"+++Other optional but useful dependencies+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++PyGame_ is needed for video and sound previews (useless if you intend to work with MoviePy on a server but really essential for advanced video editing *by hand*).++For advanced image processing you will need one or several of these packages. For instance using the method ``clip.resize`` requires that at least one of Scipy, PIL, Pillow or OpenCV are installed.++- 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.+-.. _PYPI: https://pypi.python.org/pypi/moviepy+.. _PyPI: https://pypi.python.org/pypi/moviepy+.. _Pillow: http://pillow.readthedocs.org/en/latest/.. _Zulko : https://github.com/Zulko.. _Github: https://github.com/Zulko/moviepy.. _here: http://zulko.github.io/moviepy/+.. _Scipy: http://www.scipy.org/.. _`download MoviePy`: https://github.com/Zulko/moviepy.. _`OpenCV 2.4.6`: http://sourceforge.net/projects/opencvlibrary/files/.. _Pygame: http://www.pygame.org/download.shtml-.. _`Numpy`: http://www.scipy.org/install.html+.. _Numpy: http://www.scipy.org/install.html.. _`Scikit Image`: http://scikit-image.org/download.html.. _Decorator: https://pypi.python.org/pypi/decorator.. _tqdm: https://github.com/noamraph/tqdmdiff --git a/docs/gallery.rst b/docs/gallery.rstindex e358c54c..fa7a79a3 100644--- a/docs/gallery.rst+++ b/docs/gallery.rst@@ -14,7 +14,7 @@ The (old) MoviePy reel video.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~This video was made when MoviePy was a few weeks old, it has gotten betten since. The code for most of these scenes can be found-in the :ref:`examples` section.+in the :ref:`examples`... raw:: html@@ -49,10 +49,20 @@ This video is a mix of 60 covers of the Cup Song which demonstrates non-linear vGifs edited with MoviePy--------------------------+An introductory tutorial~~~~~~~~~~~~~~~~~~~~~~~~~-This tutorial (link)+If you want to make gifs from video files, this `tutorial+<http://zulko.github.io/blog/2014/01/23/making-animated-gifs-from-video-files-with-python/>`_ gives you the basics (cutting, croping, adding text...). In the last example you will see how remove the (still) background of a video to keep only the animated part, like that:+++.. raw:: html++ <center>+ <a href="http://imgur.com/Fo2BxBK"><img src="http://i.imgur.com/Fo2BxBK.gif" title="Hosted by imgur.com"/></a>+ </center>+Programs and Scripts using MoviePy-----------------------------------@@ -60,24 +70,59 @@ Programs and Scripts using MoviePyVideogrep~~~~~~~~~~-If you liked it there is also this blog post which attempts to cut a video precisely at the beginning and end of sentences or words, and this blog post in which MoviePy automatically cuts together all the highlights of a soccer game, based on the fact that the crowd cheers louder when something interesting happens.+Videogrep is a python script written by Sam Lavigne, that goes through the subtitle tracks of movies and makes supercuts based on what it finds. For instance, here is an automatic supercut of every time the White House press secretary tells us what he can tell us:++.. raw:: html++ <center>+ <object><param name="movie"+ value="http://www.youtube.com/v/rIehsqqYFEM&hl=en_US&fs=1&rel=0">+ </param><param name="allowFullScreen" value="true"></param><param+ name="allowscriptaccess" value="always"></param><embed+ src="http://www.youtube.com/v/D7pymdCU5NQ&hl=en_US&fs=1&rel=0"+ type="application/x-shockwave-flash" allowscriptaccess="always"+ allowfullscreen="true" width="490" height="390"></embed></object>+ </center>++Here are Videogrep's introductory `blog post+<http://lav.io/2014/06/videogrep-automatic-supercuts-with-python/>`_ and the Github project `page <https://github.com/antiboredom/videogrep/>`_.++If you liked it, also have a look at these two Videogrep-inspired projects:++- This `blog post <http://zulko.github.io/blog/2014/06/21/some-more-videogreping-with-python/>`_ attempts to cut a video precisely at the beginning and end of sentences or words.+- This `other post <http://zulko.github.io/blog/2014/07/04/automatic-soccer-highlights-compilations-with-python/>`_ uses MoviePy to automatically cut together all the highlights of a soccer game, based on the fact that the crowd cheers louder when something interesting happens.MoviePy online-----------------+--------------++Websites using MoviePy for video editing automation (to be written).++.. Rinconcam-Rinconcam-~~~~~~~~~~~+.. aaa~~~~~~~~~~~-Rincomcam (link) is a camera which films surfers on the Californian beach of Point Rincon. At the end of each day it cuts together a video and puts it online. Everything is entirely automatized with Python. MoviePy is used to add transitions, titles and music to the videos.+.. Rincomcam (link) is a camera which films surfers on the Californian beach of Point Rincon. At the end of each day it cuts together a video and puts it online. Everything is entirely automatized with Python. MoviePy is used to add transitions, titles and music to the videos.MoviePy in sciences and technology-------------------------------------Piano rolls transcription to sheet music~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-This blog post explains how to transform a video of a piano roll performance into playable sheet music. MoviePy is used for the frame-by-frame analysis of the piano roll video. The last video is also edited with MoviePy:\ No newline at end of file+This `blog post <http://zulko.github.io/blog/2014/02/12/transcribing-piano-rolls/>`_ explains how to transform a video of a piano roll performance into playable sheet music. MoviePy is used for the frame-by-frame analysis of the piano roll video. The last video is also edited with MoviePy:+++.. raw:: html++ <center>+ <object><param name="movie"+ value="http://www.youtube.com/v/V2XCJNZjm4w&hl=en_US&fs=1&rel=0">+ </param><param name="allowFullScreen" value="true"></param><param+ name="allowscriptaccess" value="always"></param><embed+ src="http://www.youtube.com/v/V2XCJNZjm4w&hl=en_US&fs=1&rel=0"+ type="application/x-shockwave-flash" allowscriptaccess="always"+ allowfullscreen="true" width="490" height="390"></embed></object>+ </center>diff --git a/docs/install.rst b/docs/install.rstindex 489496ab..74b91da3 100644--- a/docs/install.rst+++ b/docs/install.rst@@ -18,7 +18,7 @@ MoviePy depends on the Python modules Numpy_, Decorator_, and tqdm_, which willLinking to ffmpeg~~~~~~~~~~~~~~~~~~-MoviePy requires a **recent version** of the software ffmpeg_ preferably downloaded directly from the ffmpeg website**.+MoviePy requires a **recent version** of the software ffmpeg_ preferably downloaded **directly from the ffmpeg website**.**Installed ffmpeg:** when you have installed ffmpeg, or (for linux users) when you have a ffmpeg binary in the ``/usr/bin`` folder, it will be detected automatically by MoviePy.diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex 2737d717..b32518a7 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -20,7 +20,8 @@ import numpy as npfrom moviepy.decorators import (apply_to_mask,requires_duration,outplace,- add_mask_if_none)+ add_mask_if_none,+ time_can_be_tuple)from moviepy.tools import (subprocess_call, verbose_print,deprecated_version_of)@@ -117,7 +118,7 @@ class VideoClip(Clip):# EXPORT OPERATIONS-+ @time_can_be_tupledef save_frame(self, filename, t=0, savemask=False):""" Save a clip's frame to an image file.@@ -571,8 +572,10 @@ class VideoClip(Clip):cmd1a = cmd1+['-r', "%.02f"%fps, filename]cmd1b = cmd1+['-f', 'image2pipe','-vcodec', 'bmp', '-']- cmd2 = [IMAGEMAGICK_BINARY, '-', '-delay', "%d"%int(100.0/fps),- '-loop', '%d'%loop]+ cmd2 = [IMAGEMAGICK_BINARY, '-delay', "%d"%int(100.0/fps),+ "-dispose" ,"%d"%(2 if dispose else 1),+ '-loop', '%d'%loop,+ '-', '-coalesce']cmd2a = cmd2+[filename]cmd2b = cmd2+['gif:-']@@ -626,7 +629,7 @@ class VideoClip(Clip):# F I L T E R I N G-+def subfx(self, fx, ta=0, tb=None, **kwargs):""" Apply a transformation to a part of the clip.@@ -881,7 +884,7 @@ class VideoClip(Clip):# CONVERSIONS TO OTHER TYPES-+ @time_can_be_tupledef to_ImageClip(self,t=0):"""Returns an ImageClip made out of the clip's frame at time ``t``@@ -1059,7 +1062,7 @@ class ImageClip(VideoClip):@outplace- def fl_time(self, time_func, apply_to =['mask', 'audio']):+ def fl_time(self, time_func, apply_to =['mask', 'audio'], keep_duration=False):""" Time-transformation filter.Applies a transformation to the clip's timelinediff --git a/moviepy/video/tools/subtitles.py b/moviepy/video/tools/subtitles.pyindex 6eaa6308..10a9a5d2 100644--- a/moviepy/video/tools/subtitles.py+++ b/moviepy/video/tools/subtitles.py@@ -3,6 +3,7 @@import reimport numpy as npfrom moviepy.video.VideoClip import VideoClip, TextClip+from moviepy.tools import cvsecsclass SubtitlesClip(VideoClip):""" A Clip that serves as "subtitle track" in videos.@@ -31,19 +32,20 @@ class SubtitlesClip(VideoClip):"""- def __init__(self, subtitles, gen_textclip=None):+ def __init__(self, subtitles, make_textclip=None):VideoClip.__init__(self)if isinstance( subtitles, str):subtitles = file_to_subtitles(subtitles)+ subtitles = [(map(cvsecs, tt),txt) for tt, txt in subtitles]self.subtitles = subtitlesself.textclips = dict()- if gen_textclip is None:- gen_textclip = lambda txt: TextClip(txt, font='Georgia-Bold',+ if make_textclip is None:+ make_textclip = lambda txt: TextClip(txt, font='Georgia-Bold',fontsize=24, color='white',stroke_color='black', stroke_width=0.5)- self.gen_textclip = gen_textclip+ self.make_textclip = make_textclipself.start=0self.duration = max([tb for ((ta,tb), txt) in self.subtitles])self.end=self.duration@@ -58,7 +60,7 @@ class SubtitlesClip(VideoClip):return Falsesub = sub[0]if sub not in self.textclips.keys():- self.textclips[sub] = gen_textclip(sub[1])+ self.textclips[sub] = self.make_textclip(sub[1])return subdef get_frame(t):@@ -73,15 +75,42 @@ class SubtitlesClip(VideoClip):self.get_frame = get_frameself.mask = VideoClip(ismask=True, get_frame=mask_get_frame)++ def __iter__(self):+ return self.subtitles.__iter__()++ def __getitem__(self, k):+ return self.subtitles[k]++ def __str__(self):++ def to_srt(sub_element):+ (ta, tb), txt = sub_element+ fta, ftb = map(time_to_string, (ta, tb))+ return "%s - %s\n%s"%(fta, ftb, txt)++ return "\n\n".join(map(to_srt, self.subtitles))++ def match_expr(self, expr):+ return SubtitlesClip([e for e in self.subtitles+ if re.find(expr, e) != []])++ def write_srt(self, filename):+ with open(filename, 'w+') as f:+ f.write(str(self))-def convert_time(timestring):+def string_to_time(timestring):""" Converts a string into seconds """nums = map(float, re.findall(r'\d+', timestring))return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000+def time_to_string(timestring):+ """ Converts a string into seconds """+ nums = map(float, re.findall(r'\d+', timestring))+ return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000def file_to_subtitles(filename):""" Converts a srt file into subtitles.@@ -101,7 +130,7 @@ def file_to_subtitles(filename):for line in lines:times = re.findall("[0-9]*:[0-9]*:[0-9]*,[0-9]*", line)if times != []:- current_times = map(convert_time, times)+ current_times = map(time_to_string, times)elif line == '\n':times_texts.append((current_times, current_text.strip('\n')))current_times, current_text = None, ""