Video editing with Python
added downloader. Fixed transparency bug.
Zulko73dfdaad3068
diff --git a/README.rst b/README.rstindex bd0ab6dd..6638a428 100644--- a/README.rst+++ b/README.rst@@ -16,19 +16,15 @@ In this example we open a video file, select the subclip between t=50s and t=60sfrom moviepy.editor import *- # Load myHolidays.mp4 and select the subclip 00:00:50 - 00:00:60- clip = VideoFileClip("myHolidays.mp4").subclip(50,60)+ video = VideoFileClip("myHolidays.mp4").subclip(50,60)- # Generate a 10-second centered text clip (many options available ! )+ # Make the text. Many more options are available.txt_clip = ( TextClip("My Holidays 2013",fontsize=70,color='white').set_position('center').set_duration(10) )- # Overlay the text clip above the first clip- final_clip = CompositeVideoClip([clip, txt_clip])-- # write the result to a file in any format- final_clip.to_videofile("myHolidays_edited.webm",fps=25)+ result = CompositeVideoClip([video, txt_clip]) # Overlay text on video+ result.write_videofile("myHolidays_edited.webm",fps=25) # Many options...@@ -43,13 +39,13 @@ You can also discuss about the project on Reddit_ or on the mailing list moviepyInstallation---------------MoviePy depends on the Python modules Numpy_, imageio_, Decorator_, and tqdm_, which will be automatically installed during MoviePy's installation. It also depends on the software FFMPEG, which should be automatically downloaded/installed by ImageIO during your first use of MoviePy (it takes a few seconds). If you want to use a specific version of FFMPEG, follow the instructions in file ``config_defaults.py``. In case of trouble, provide feedback.+MoviePy depends on the Python modules Numpy_, imageio_, Decorator_, and tqdm_, which will be automatically installed during MoviePy's installation. The software FFMPEG should be automatically downloaded/installed (by imageio) during your first use of MoviePy (it takes a few seconds). If you want to use a specific version of FFMPEG, follow the instructions in file ``config_defaults.py``. In case of trouble, provide feedback.**Installation 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-**Installation with pip:** if you have ``pip`` installed, just type this in a terminal (it will install ez_setup if you don't already have it) ::+**Installation with pip:** if you have ``pip`` installed, just type this in a terminal: ::(sudo) pip install moviepydiff --git a/docs/gallery.rst b/docs/gallery.rstindex 39a6f8bc..786924ff 100644--- a/docs/gallery.rst+++ b/docs/gallery.rst@@ -13,7 +13,7 @@ Videos edited with MoviepyThe Cup Song Covers Mix~~~~~~~~~~~~~~~~~~~~~~~~-This mix of 60 covers of the Cup Song demonstrates the non-linear video editing capabilities of MoviePy. Here is `the (undocumented) MoviePy code <http://nbviewer.ipython.org/github/Zulko/--video-editing---Cup-Song-Covers-Mix/blob/master/CupSongsCovers.ipynb>`_ that generated the script.+This mix of 60 covers of the Cup Song demonstrates the non-linear video editing capabilities of MoviePy. Here is `the (undocumented) MoviePy code <http://nbviewer.ipython.org/github/Zulko/--video-editing---Cup-Song-Covers-Mix/blob/master/CupSongsCovers.ipynb>`_ that generated the video... raw:: html@@ -43,7 +43,7 @@ Animations edited with MoviePy-------------------------------GIFs made from video files+GIFs made from videos~~~~~~~~~~~~~~~~~~~~~~~~~~~~This `tutorial@@ -111,6 +111,11 @@ Or use `this script <https://gist.github.com/Zulko/b910c8b22e8e1c01fae6>`_ to ma</iframe></div>+Data animations+----------------++This `tutorial <http://zulko.github.io/blog/2014/11/13/things-you-can-do-with-python-and-pov-ray/>`_ shows how to use MoviePy to animate the different Python vizualization libraries: Mayavi, Vispy, Scikit-image, Matplotlib, etc.+Scientific or technological projects-------------------------------------diff --git a/moviepy/editor.py b/moviepy/editor.pyindex 64285549..0bf2feeb 100644--- a/moviepy/editor.py+++ b/moviepy/editor.py@@ -21,6 +21,7 @@ clip.preview().from .video.io.VideoFileClip import VideoFileClipfrom .video.io.ImageSequenceClip import ImageSequenceClip+from .video.io.downloader import download_webfilefrom .video.VideoClip import VideoClip, ImageClip, ColorClip, TextClipfrom .video.compositing.CompositeVideoClip import CompositeVideoClip, clips_arrayfrom .video.compositing.concatenate import concatenate_videoclips, concatenate # concatenate=deprecateddiff --git a/moviepy/version.py b/moviepy/version.pyindex e0f354da..69601a5f 100644--- a/moviepy/version.py+++ b/moviepy/version.py@@ -1 +1 @@-__version__ = "0.2.2.01"+__version__ = "0.2.2.02"diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex 269b17e1..f7666b59 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -93,7 +93,8 @@ class VideoClip(Clip):"""- def __init__(self, make_frame=None, ismask=False, duration=None):+ def __init__(self, make_frame=None, ismask=False, duration=None,+ has_constant_size=True):Clip.__init__(self)self.mask = Noneself.audio = None@@ -103,6 +104,7 @@ class VideoClip(Clip):self.make_frame = make_frameself.size = self.get_frame(0).shape[:2][::-1]self.ismask = ismask+ self.has_constant_size=has_constant_sizeif duration is not None:self.duration = durationself.end = duration@@ -521,11 +523,10 @@ class VideoClip(Clip):by the clip's ``pos`` attribute. Meant for compositing."""- hf, wf = sizef = picture.shape[:2]+ hf, wf = framesize = picture.shape[:2]if self.ismask and picture.max() != 0:- return np.maximum(picture,- self.blit_on(np.zeros(sizef), t))+ return np.minimum(1, picture + self.blit_on(np.zeros(framesize), t))ct = t - self.start # clip time@@ -569,7 +570,7 @@ class VideoClip(Clip):return blit(img, picture, pos, mask=mask, ismask=self.ismask)- def add_mask(self, constant_size=True):+ def add_mask(self):""" Add a mask VideoClip to the VideoClip.Returns a copy of the clip with a completely opaque mask@@ -579,11 +580,11 @@ class VideoClip(Clip):Set ``constant_size`` to `False` for clips with movingimage size."""- if constant_size:+ if self.has_constant_size:mask = ColorClip(self.size, 1.0, ismask=True)return self.set_mask(mask.set_duration(self.duration))else:- make_frame = lambda t: np.ones(self.get_frame(t).shape, dtype=float)+ make_frame = lambda t: np.ones(self.get_frame(t).shape[:2], dtype=float)mask = VideoClip(ismask=True, make_frame=make_frame)return self.set_mask(mask.set_duration(self.duration))diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.pyindex e3a6d43a..30172b78 100644--- a/moviepy/video/compositing/CompositeVideoClip.py+++ b/moviepy/video/compositing/CompositeVideoClip.py@@ -12,6 +12,7 @@ class CompositeVideoClip(VideoClip):base class for most compositions.Parameters+ ----------sizeThe size (height x width) of the final clip.@@ -32,6 +33,12 @@ class CompositeVideoClip(VideoClip):bg_colorColor for the unmasked and unfilled regions. Set to None for theseregions to be transparent (will be slower).++ use_bgclip+ Set to True if the first clip in the list should be used as the+ 'background' on which all other clips are blitted. That first clip must+ have the same size as the final clip. If it has no transparency, the final+ clip will have no mask.If all clips with a fps attribute have the same fps, it becomes the fps ofthe result.@@ -43,15 +50,17 @@ class CompositeVideoClip(VideoClip):if size is None:size = clips[0].size-- if bg_color is None:- bg_color = 0.0 if ismask else (0, 0, 0)+if use_bgclip and (clips[0].mask is None):transparent = Falseelse:transparent = (bg_color is None)+ if bg_color is None:+ bg_color = 0.0 if ismask else (0, 0, 0)++fps_list = list(set([c.fps for c in clips if hasattr(c,'fps')]))if len(fps_list)==1:self.fps= fps_list[0]@@ -85,11 +94,12 @@ class CompositeVideoClip(VideoClip):# compute mask if necessaryif transparent:- maskclips = [c.mask.set_pos(c.pos) for c in self.clips- if c.mask is not None]- if maskclips != []:- self.mask = CompositeVideoClip(maskclips,self.size, ismask=True,- bg_color=0)+ maskclips = [(c.mask if (c.mask is not None) else+ c.add_mask().mask).set_pos(c.pos)+ for c in self.clips]++ self.mask = CompositeVideoClip(maskclips,self.size, ismask=True,+ bg_color=0.0)def make_frame(t):""" The clips playing at time `t` are blitted over onediff --git a/moviepy/video/io/VideoFileClip.py b/moviepy/video/io/VideoFileClip.pyindex 4bb3a3c1..b61408f8 100644--- a/moviepy/video/io/VideoFileClip.py+++ b/moviepy/video/io/VideoFileClip.py@@ -27,7 +27,7 @@ class VideoFileClip(VideoClip):Video files rarely contain masks, but some video codecs enablethat. For istance if you have a MoviePy VideoClip with a mask youcan save it to a videofile with a mask. (see also- ``VideoClip.to_videofile`` for more details).+ ``VideoClip.write_videofile`` for more details).audio:Set to `False` if the clip doesn't have any audio or if you do notdiff --git a/moviepy/video/io/downloader.py b/moviepy/video/io/downloader.pynew file mode 100644index 00000000..5d28373b--- /dev/null+++ b/moviepy/video/io/downloader.py@@ -0,0 +1,25 @@+"""+Utilities to get a file from the internet+"""++import os+from urllib import urlretrieve+from moviepy.tools import subprocess_call+++def download_webfile(url, filename, overwrite=False):+ """ Small utility to download the file at 'url' under name 'filename'.+ If url is a youtube video ID like z410eauCnH it will download the video+ using youtube-dl (install youtube-dl first !).+ If the filename already exists and overwrite=False, nothing will happen.+ """+ if os.path.exists(filename) and not overwrite:+ return++ if '.' in url:+ urlretrieve(url, filename)+ else:+ subprocess_call(['youtube-dl', url, '-o', filename])+++diff --git a/moviepy/video/tools/cuts.py b/moviepy/video/tools/cuts.pyindex a56653e9..5a5080bb 100644--- a/moviepy/video/tools/cuts.py+++ b/moviepy/video/tools/cuts.py@@ -38,10 +38,10 @@ class FrameMatches(list):list.__init__(self, sorted(lst, key=lambda e: e.distance))- def best(self, n=None, percent=None):+ def best(self, n=1, percent=None):if percent is not None:n = len(self)*percent/100- return FrameMatches(self[:n])+ return self[0] if n==1 else FrameMatches(self[:n])def filter(self, fun):return FrameMatches(filter(fun, self))@@ -53,19 +53,49 @@ class FrameMatches(list):def load(filename):arr = np.loadtxt(filename)mfs = [FrameMatch(*e) for e in arr]+ return FramesMatches(mfs)def find_matching_frames(clip, dist_thr, max_d, fps=None):- """ Returns a list [(t1, t2, distance), ...] for all pairs of frames with- (t2-t1 < max_d). Optimized routine. Quite fast.+ """ Finds all the frames tht look alike in a clip, for instance to make a+ looping gif.- clip : a MoviePy video clip, possibly transformed/resized- dist_thr: distance above which a match is rejected- max_d: maximal duration (in seconds) between two matching frames- fps: frames per second (default will be clip.fps)+ This teturns a FramesMatches object of the all pairs of frames with+ (t2-t1 < max_d) and whose distance is under dist_thr.++ This is well optimized routine and quite fast.++ Examples+ ---------++ We find all matching frames in a given video and turn the best match with+ a duration of 1.5s or more into a GIF:++ >>> from moviepy.editor import VideoFileClip+ >>> from moviepy.video.tools.cuts import find_matching_frames+ >>> clip = VideoFileClip("foo.mp4").resize(width=200)+ >>> matches = find_matching_frames(clip, 10, 3) # will take time+ >>> best = matches.filter(lambda m: m.time_span > 1.5).best()+ >>> clip.subclip(best.t1, best.t2).write_gif("foo.gif")++ Parameters+ -----------++ clip+ A MoviePy video clip, possibly transformed/resized++ dist_thr+ Distance above which a match is rejected++ max_d+ Maximal duration (in seconds) between two matching frames++ fps+ Frames per second (default will be clip.fps)+"""N_pixels = clip.w * clip.h * 3diff --git a/moviepy/video/tools/subtitles.py b/moviepy/video/tools/subtitles.pyindex 81851356..5e8fada3 100644--- a/moviepy/video/tools/subtitles.py+++ b/moviepy/video/tools/subtitles.py@@ -36,7 +36,7 @@ class SubtitlesClip(VideoClip):def __init__(self, subtitles, make_textclip=None):- VideoClip.__init__(self)+ VideoClip.__init__(self, has_constant_size=False)if isinstance( subtitles, str):subtitles = file_to_subtitles(subtitles)@@ -57,6 +57,9 @@ class SubtitlesClip(VideoClip):self.end=self.durationdef add_textclip_if_none(t):+ """ Will generate a textclip if it hasn't been generated asked+ to generate it yet. If there is no subtitle to show at t, return+ false. """sub =[((ta,tb),txt) for ((ta,tb),txt) in self.textclips.keys()if (ta<=t<tb)]if sub == []:@@ -67,6 +70,7 @@ class SubtitlesClip(VideoClip):sub = sub[0]if sub not in self.textclips.keys():self.textclips[sub] = self.make_textclip(sub[1])+return subdef make_frame(t):@@ -80,7 +84,8 @@ class SubtitlesClip(VideoClip):else np.array([[0]]))self.make_frame = make_frame- self.mask = VideoClip(make_mask_frame, ismask=True)+ hasmask = (self.make_textclip('T').mask is not None)+ self.mask = (VideoClip(make_mask_frame, ismask=True) if hasmask else None)def in_subclip(self, t_start= None, t_end= None):""" Returns a sequence of [(t1,t2), txt] covering all the given subclipdiff --git a/setup.py b/setup.pyindex 81ba551e..78d7bf27 100644--- a/setup.py+++ b/setup.py@@ -23,6 +23,6 @@ setup(name='moviepy',description='Video editing with Python',long_description=open('README.rst').read(),license='see LICENSE.txt',- keywords="video editing audio compositing numpy ffmpeg ",+ keywords="video editing audio compositing ffmpeg",packages= find_packages(exclude='docs'),install_requires= ['numpy', 'decorator', 'imageio', 'tqdm'])