Video editing with Python
Fixed resizing with masks. added 'all' in vfx/afx. added mask_and/or/inv. fixed vfx.mirror_x/y
Zulko234948507bf2
diff --git a/moviepy/Clip.py b/moviepy/Clip.pyindex bf30894d..545c4e0f 100644--- a/moviepy/Clip.py+++ b/moviepy/Clip.py@@ -376,7 +376,7 @@ class Clip:return newclip@requires_duration- def iter_frames(self, fps=None, progress_bar=False):+ def iter_frames(self, fps=None, with_times = False, progress_bar=False):""" Iterates over all the frames of the clip.Returns each frame of the clip as a HxWxN np.array,@@ -402,10 +402,13 @@ class Clip:if fps is None:fps = self.fps-+def generator():for t in np.arange(0, self.duration, 1.0/fps):- yield self.get_frame(t)+ if with_times:+ yield t, self.get_frame(t)+ else:+ yield self.get_frame(t)if progress_bar:nframes = int(self.duration*fps)+1diff --git a/moviepy/audio/fx/__init__.py b/moviepy/audio/fx/__init__.pyindex aec556c7..67fe3b19 100644--- a/moviepy/audio/fx/__init__.py+++ b/moviepy/audio/fx/__init__.py@@ -1,14 +1,4 @@"""-Contains transformation functions (clip->clip)+This module contains transformation functions (clip->clip)One file for one fx. The file's name is the fx's name"""--import os-directory = os.path.dirname(os.path.realpath(__file__))-files = sorted(os.listdir(directory))-fx_list = [f for f in files if ( f.endswith('py') and not f.startswith('_'))]--__all__ = [c[:-3] for c in fx_list]--for name in __all__:- exec("from .%s import %s"%(name,name))diff --git a/moviepy/audio/fx/all/__init__.py b/moviepy/audio/fx/all/__init__.pynew file mode 100644index 00000000..4c96acfd--- /dev/null+++ b/moviepy/audio/fx/all/__init__.py@@ -0,0 +1,19 @@+"""+Loads all the fx !+Usage:+import moviepy.audio.fx.all as afx+audio_clip = afx.volume_x(some_clip, .5)+"""++import os++directory = os.path.dirname(+ os.path.dirname(+ os.path.realpath(__file__)))++files = os.listdir(directory)+fx_list = [f for f in files if ( f.endswith('.py') and not f.startswith('_'))]+__all__ = [c[:-3] for c in fx_list]++for name in __all__:+ exec("from ..%s import %s"%(name,name))\ No newline at end of filediff --git a/moviepy/editor.py b/moviepy/editor.pyindex 0848f402..0f32bd8a 100644--- a/moviepy/editor.py+++ b/moviepy/editor.py@@ -30,8 +30,8 @@ from .audio.io.AudioFileClip import AudioFileClip# FX-import moviepy.video.fx as vfx-import moviepy.audio.fx as afx+import moviepy.video.fx.all as vfx+import moviepy.audio.fx.all as afximport moviepy.video.compositing.transitions as transfx# Tools@@ -48,30 +48,37 @@ except ImportError:# The next loop transforms many effects into VideoClip methods so that# they can be walled with myclip.resize(width=500) instead of# myclip.fx( vfx.resize, width= 500)-for method in ["vfx.crop",- "vfx.loop",- "vfx.resize",- "vfx.margin",- "vfx.fadein",- "vfx.fadeout",- "vfx.speedx",- "afx.volumex",- "afx.audio_fadein",- "afx.audio_fadeout",- "transfx.crossfadein",- "transfx.crossfadeout"]:+for method in [+ "afx.audio_fadein",+ "afx.audio_fadeout",+ "afx.volumex",+ "transfx.crossfadein",+ "transfx.crossfadeout",+ "vfx.crop",+ "vfx.fadein",+ "vfx.fadeout",+ "vfx.loop",+ "vfx.margin",+ "vfx.mask_and",+ "vfx.mask_inv",+ "vfx.mask_or",+ "vfx.resize",+ "vfx.speedx"+ ]:exec("VideoClip.%s = %s"%( method.split('.')[1], method))for method in ["afx.audio_fadein","afx.audio_fadeout","afx.audio_loop",- "afx.volumex"]:+ "afx.volumex"+ ]:exec("AudioClip.%s = %s"%( method.split('.')[1], method))#------------------------------------------------------------------# Previews: try to import pygame+# Previews: try to import pygame, else make methods which raise+# exceptions saying to install PyGame# Add methods preview and show (only if pygame installed)diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex f2a39c2c..563db6d2 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -136,6 +136,7 @@ class VideoClip(Clip):def write_videofile(self, filename, fps=24, codec='libx264',bitrate=None, audio=True, audio_fps=44100,+ preset="medium",audio_nbytes = 4, audio_codec= 'libmp3lame',audio_bitrate = None, audio_bufsize = 2000,temp_audiofile=None,@@ -278,61 +279,36 @@ class VideoClip(Clip):videofile = filename# enough cpu for multiprocessing ?- enough_cpu = (multiprocessing.cpu_count() > 2)+ enough_cpu = (multiprocessing.cpu_count() > 1)verbose_print(verbose, "\nMoviePy: building video file %s\n"%filename+40*"-"+"\n")- if para and make_audio and enough_cpu:-- # Parallelize- verbose_print(verbose, "Writing audio/video in parrallel.\n")- audioproc = multiprocessing.Process(- target=self.audio.write_audiofile,- args=(temp_audiofile,audio_fps,audio_nbytes,- audio_bufsize,audio_codec,- audio_bitrate,- verbose))-- audioproc.start()-- ffmpeg_write_video(self,- videofile, fps, codec,- bitrate=bitrate,- write_logfile=write_logfile,- verbose=verbose)- audioproc.join()- if audioproc.exitcode:- print ("WARNING: something went wrong with the audio"+- " writing, Exit code %d"%audioproc.exitcode)- else:-- # Don't parallelize- if make_audio:- self.audio.write_audiofile(temp_audiofile,audio_fps,- audio_nbytes, audio_bufsize,- audio_codec, bitrate=audio_bitrate,- write_logfile=write_logfile,- verbose=verbose)-- ffmpeg_write_video(self,- videofile, fps, codec,- bitrate=bitrate,- write_logfile=write_logfile,- verbose=verbose)-- # Merge with audio if any and trash temporary files.++ if make_audio:+ self.audio.write_audiofile(temp_audiofile,audio_fps,+ audio_nbytes, audio_bufsize,+ audio_codec, bitrate=audio_bitrate,+ write_logfile=write_logfile,+ verbose=verbose)++ ffmpeg_write_video(self, videofile, fps, codec,+ bitrate=bitrate,+ preset=preset,+ write_logfile=write_logfile,+ verbose=verbose)++ # Merge with audio if any and trash temporary files.if merge_audio:-verbose_print(verbose, "\n\nNow merging video and audio:\n")ffmpeg_merge_video_audio(videofile,temp_audiofile,filename, ffmpeg_output=True)- if remove_temp:- os.remove(videofile)- if not isinstance(audio,str):- os.remove(temp_audiofile)- verbose_print(verbose, "\nYour video is ready !\n")+ if remove_temp:+ os.remove(videofile)+ if make_audio:+ os.remove(temp_audiofile)+ verbose_print(verbose, "\nYour video is ready !\n")def write_images_sequence(self, nameformat, fps=None, verbose=True):@@ -571,7 +547,7 @@ class VideoClip(Clip):cmd1a = cmd1+['-r', "%.02f"%fps, filename]cmd1b = cmd1+['-f', 'image2pipe','-vcodec', 'bmp', '-']- cmd2 = [IMAGEMAGICK_BINARY, '-delay', "%d"%int(100.0/fps),+ cmd2 = [IMAGEMAGICK_BINARY, '-delay', "%.02f"%(100.0/fps),"-dispose" ,"%d"%(2 if dispose else 1),'-loop', '%d'%loop,'-', '-coalesce']@@ -593,11 +569,10 @@ class VideoClip(Clip):verbose_print(verbose, "\nMoviePy: building GIF file %s\n"%filename+40*"-"+"\n")verbose_print(verbose, "Generating GIF frames...\n")- nframes = int(self.duration*fps)+1try:- for frame in tqdm(self.iter_frames(fps=fps), total=nframes):+ for frame in self.iter_frames(fps=fps, progress_bar=True):proc1.stdin.write(frame.tostring())verbose_print(verbose, "Done.\n")@@ -741,7 +716,7 @@ class VideoClip(Clip):mask = ColorClip(self.size, 1.0, ismask=True)return self.set_mask( mask.set_duration(self.duration))else:- get_frame = lambda t: np.ones(self.get_frame(t).shape)+ get_frame = lambda t: np.ones(self.get_frame(t).shape, dtype=float)mask = VideoClip(ismask=True, get_frame = get_frame)return self.set_mask(mask.set_duration(self.duration))@@ -884,12 +859,14 @@ class VideoClip(Clip):@time_can_be_tuple- def to_ImageClip(self,t=0):+ def to_ImageClip(self,t=0, with_mask=True):"""Returns an ImageClip made out of the clip's frame at time ``t``"""- return ImageClip(self.get_frame(t))-+ newclip = ImageClip(self.get_frame(t), ismask=self.ismask)+ if with_mask and self.mask is not None:+ newclip.mask = self.mask.to_ImageClip(t)+ return newclipdef to_mask(self, canal=0):@@ -1056,7 +1033,7 @@ class ImageClip(VideoClip):a = getattr(self, attr)if a != None:new_a = a.fl_image(image_func)- setattr(newclip, attr, new_a)+ setattr(self, attr, new_a)diff --git a/moviepy/video/fx/__init__.py b/moviepy/video/fx/__init__.pyindex 2d8c3638..67fe3b19 100644--- a/moviepy/video/fx/__init__.py+++ b/moviepy/video/fx/__init__.py@@ -1,14 +1,4 @@"""-Contains transformation functions (clip->clip)+This module contains transformation functions (clip->clip)One file for one fx. The file's name is the fx's name"""--import os--directory = os.path.dirname(os.path.realpath(__file__))-files = os.listdir(directory)-fx_list = [f for f in files if ( f.endswith('.py') and not f.startswith('_'))]-__all__ = [c[:-3] for c in fx_list]--for name in __all__:- exec("from .%s import %s"%(name,name))diff --git a/moviepy/video/fx/all/__init__.py b/moviepy/video/fx/all/__init__.pynew file mode 100644index 00000000..377e4673--- /dev/null+++ b/moviepy/video/fx/all/__init__.py@@ -0,0 +1,21 @@+"""+Loads all the fx !+Usage:+import moviepy.video.fx.all as vfx+clip = vfx.resize(some_clip, width=400)+clip = vfx.mirror_x(some_clip)+"""++import os+++directory = os.path.dirname(+ os.path.dirname(+ os.path.realpath(__file__)))++files = os.listdir(directory)+fx_list = [f for f in files if ( f.endswith('.py') and not f.startswith('_'))]+__all__ = [c[:-3] for c in fx_list]++for name in __all__:+ exec("from ..%s import %s"%(name,name))\ No newline at end of filediff --git a/moviepy/video/fx/mask_and.py b/moviepy/video/fx/mask_and.pynew file mode 100644index 00000000..9b5c21dd--- /dev/null+++ b/moviepy/video/fx/mask_and.py@@ -0,0 +1,18 @@+import numpy as np+from ..VideoClip import ImageClip++def mask_and(clip, other_clip):+ """ Returns the logical 'and' (min) between two masks.+ other_clip can be a mask clip or a picture (np.array).+ The result has the duration of 'clip' (if it has any)+ """++ # To ensure that 'or' of two ImageClips will be an ImageClip.+ if isinstance(other_clip, ImageClip):+ other_clip = other_clip.img++ if isinstance(other_clip, np.ndarray):+ return clip.fl_image(lambda f : np.minimum(f, other_clip))+ else:+ return clip.fl(lambda gf, t : np.minimum(gf(t),+ other_clip.get_frame(t)))\ No newline at end of filediff --git a/moviepy/video/fx/mask_inv.py b/moviepy/video/fx/mask_inv.pynew file mode 100644index 00000000..c74fb0de--- /dev/null+++ b/moviepy/video/fx/mask_inv.py@@ -0,0 +1,3 @@+def mask_inv(clip):+ """ Returns the color-inversed mask."""+ return clip.fl_image(lambda f : 1.0 - f)\ No newline at end of filediff --git a/moviepy/video/fx/mask_or.py b/moviepy/video/fx/mask_or.pynew file mode 100644index 00000000..66af2088--- /dev/null+++ b/moviepy/video/fx/mask_or.py@@ -0,0 +1,18 @@+import numpy as np+from ..VideoClip import ImageClip++def mask_or(clip, other_clip):+ """ Returns the logical 'or' (max) between two masks.+ other_clip can be a mask clip or a picture (np.array).+ The result has the duration of 'clip' (if it has any)+ """++ # To ensure that 'or' of two ImageClips will be an ImageClip.+ if isinstance(other_clip, ImageClip):+ other_clip = other_clip.img++ if isinstance(other_clip, np.ndarray):+ return clip.fl_image(lambda f : np.maximum(f, other_clip))+ else:+ return clip.fl(lambda gf, t : np.maximum(gf(t),+ other_clip.get_frame(t)))\ No newline at end of filediff --git a/moviepy/video/fx/mirror_x.py b/moviepy/video/fx/mirror_x.pyindex 2a1daebc..3173dac5 100644--- a/moviepy/video/fx/mirror_x.py+++ b/moviepy/video/fx/mirror_x.py@@ -1,5 +1,4 @@def mirror_x(clip, apply_to= "mask"):""" flips the clip horizontally (and its mask too, by default) """- return clip.fl_image(lambda gf, t: gf(t)[:,::-1],- apply_to = apply_to)+ return clip.fl_image(lambda f: f[:,::-1], apply_to = apply_to)diff --git a/moviepy/video/fx/mirror_y.py b/moviepy/video/fx/mirror_y.pyindex db205423..0a602e9f 100644--- a/moviepy/video/fx/mirror_y.py+++ b/moviepy/video/fx/mirror_y.py@@ -1,4 +1,3 @@def mirror_y(clip, apply_to= "mask"):""" flips the clip vertically (and its mask too, by default) """- return clip.fl_image(lambda gf, t : gf(t)[::-1],- apply_to = apply_to)+ return clip.fl_image(lambda f : f[::-1], apply_to = apply_to)diff --git a/moviepy/video/fx/resize.py b/moviepy/video/fx/resize.pyindex 5d0c7730..a37c78a2 100644--- a/moviepy/video/fx/resize.py+++ b/moviepy/video/fx/resize.py@@ -6,6 +6,7 @@ try:resizer = lambda pic, newsize : cv2.resize(pic.astype('uint8'),tuple(map(int, newsize)),interpolation=cv2.INTER_AREA)+ resizer.origin = "cv2"except ImportError:@@ -26,6 +27,7 @@ except ImportError:resized_pil = pilim.resize(newsize[::-1], Image.ANTIALIAS)arr = np.fromstring(resized_pil.tostring(), dtype='uint8')return arr.reshape(newshape)+ resizer.origin = "PIL"except ImportError:# TRY USING SCIPY AS RESIZER@@ -33,6 +35,7 @@ except ImportError:from scipy.misc import imresizeresizer = lambda pic, newsize : imresize(pic,map(int, newsize[::-1]))+ resizer.origin = "Scipy"except ImportError:resize_possible = False@@ -73,6 +76,7 @@ def resize(clip, newsize=None, height=None, width=None, apply_to_mask=True):>>> myClip.resize(lambda t : 1+0.02*t) # slow swelling of the clip"""+w, h = clip.sizeif newsize != None:@@ -90,9 +94,8 @@ def resize(clip, newsize=None, height=None, width=None, apply_to_mask=True):if clip.ismask:- fun = lambda gf,t: (1.0*resizer((255 * gf(t))- .astype('uint8'),- newsize2(t))/255)+ fun = lambda gf,t: (1.0*resizer((255 * gf(t)).astype('uint8'),+ newsize2(t))/255)else:fun = lambda gf,t: resizer(gf(t).astype('uint8'),@@ -126,17 +129,20 @@ def resize(clip, newsize=None, height=None, width=None, apply_to_mask=True):newsize = [width, h * width / w]-+ # From here, the resizing is constant (not a function of time), size=newsize+if clip.ismask:-- fl = lambda pic: 1.0*resizer((255 * pic).astype('uint8'),- newsize)/255+ fl = lambda pic: 1.0*resizer((255 * pic).astype('uint8'), newsize)/255.0else:-fl = lambda pic: resizer(pic.astype('uint8'), newsize)- return clip.fl_image(fl, apply_to= (["mask"] if apply_to_mask else []))+ newclip = clip.fl_image(fl)++ if apply_to_mask and clip.mask is not None:+ newclip.mask = resize(clip.mask, newsize, apply_to_mask=False)++ return newclipif not resize_possible:diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.pyindex 4bb35fce..26fb7d01 100644--- a/moviepy/video/io/ffmpeg_reader.py+++ b/moviepy/video/io/ffmpeg_reader.py@@ -1,3 +1,8 @@+"""+This module implements all the functions to read a video or a picture+using ffmpeg. It is quite ugly, as there are many pitfalls to avoid+"""+from __future__ import divisionimport subprocess as sp@@ -123,11 +128,6 @@ class FFMPEG_VideoReader:"""# these definitely need to be rechecked sometime. Seems to work.- #pos = min( self.nframes, int(np.round(self.fps*t))+1 )- #if pos > self.nframes:- # raise ValueError(("Video file %s has only %d frames but"- # " frame #%d asked")%(- # self.filename, self.nframes, pos))pos = int(self.fps*t)+1@@ -252,14 +252,36 @@ def ffmpeg_parse_infos(filename, print_infos=False):result['video_size'] = s- # get the frame rate. Sometimes it's 'tbr', sometimes 'fps'...+ # get the frame rate. Sometimes it's 'tbr', sometimes 'fps', sometimes+ # tbc, and sometimes tbc/2... Trust tbc first, then tbr, then fps.try:match = re.search("( [0-9]*.| )[0-9]* tbr", line)- result['video_fps'] = float(line[match.start():match.end()].split(' ')[1])+ tbr = float(line[match.start():match.end()].split(' ')[1])++ try:+ match = re.search("( [0-9]*.| )[0-9]* tbc", line)+ tbc = float(line[match.start():match.end()].split(' ')[1])+ if abs(tbr - tbc/2) < abs(tbr-tbc):+ result['video_fps'] = 1.0*tbc /2+ else:+ result['video_fps'] = tbc+ except:+ result['video_fps'] = tbr++except:match = re.search("( [0-9]*.| )[0-9]* fps", line)result['video_fps'] = float(line[match.start():match.end()].split(' ')[1])++ # It is known that a fps of 24 is often written as 24000/1001+ # but then ffmpeg nicely rounds it to 23.98, which we hate.+ coef = 1000.0/1001.0+ fps = result['video_fps']+ for x in [23,24,25]:+ if (fps!=x) and abs(fps - x*coef) < .01:+ result['video_fps'] = x*coef+result['video_nframes'] = int(result['duration']*result['video_fps'])+1result['video_duration'] = result['duration']diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.pyindex e536d3d8..008a309d 100644--- a/moviepy/video/io/ffmpeg_writer.py+++ b/moviepy/video/io/ffmpeg_writer.py@@ -53,6 +53,11 @@ class FFMPEG_VideoWriter:is used. If the video dimensions are not both even (e.g. 720x405)another pixel format is used, and this can cause problem in somevideo readers.++ preset+ Sets the time that FFMPEG will take to compress the video. The slower,+ the better the compression rate. Possibilities are: ultrafast,superfast,+ veryfast, faster, fast, medium (default), slow, slower, veryslow, placebo.bitrateOnly relevant for codecs which accept a bitrate. "5000k" offers@@ -67,7 +72,8 @@ class FFMPEG_VideoWriter:def __init__(self, filename, size, fps, codec="libx264",- bitrate=None, withmask=False, logfile=None):+ preset="medium", bitrate=None, withmask=False,+ logfile=None):if logfile is None:logfile = sp.PIPE@@ -85,7 +91,8 @@ class FFMPEG_VideoWriter:'-pix_fmt', "rgba" if withmask else "rgb24",'-r', "%.02f"%fps,'-i', '-', '-an',- '-vcodec', codec]+ '-vcodec', codec,+ '-preset', preset]+ (['-b',bitrate] if (bitrate!=None) else [])# http://trac.ffmpeg.org/ticket/658@@ -105,7 +112,7 @@ class FFMPEG_VideoWriter:def write_frame(self,img_array):- """ Writes 1 frame in the file ! """+ """ Writes one frame in the file."""try:self.proc.stdin.write(img_array.tostring())except IOError as err:@@ -150,7 +157,8 @@ class FFMPEG_VideoWriter:del self.procdef ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,- withmask=False, write_logfile=False, verbose=True):+ preset = "medium", withmask=False, write_logfile=False,+ verbose=True):if write_logfile:logfile = open(filename + ".log", 'w+')@@ -160,14 +168,15 @@ def ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,verbose_print(verbose, "\nWriting video into %s\n"%filename)writer = FFMPEG_VideoWriter(filename, clip.size, fps, codec = codec,- bitrate=bitrate, logfile=logfile)+ preset=preset, bitrate=bitrate,+ logfile=logfile)nframes = int(clip.duration*fps)- for i in tqdm(range(nframes)):- frame = clip.get_frame(1.0*i/fps)+ for t,frame in clip.iter_frames(progress_bar=True, with_times=True,+ fps=fps):if withmask:- mask = (255*clip.mask.get_frame(1.0*i/fps))+ mask = 255*clip.mask.get_frame(t)frame = np.dstack([frame,mask])writer.write_frame(frame.astype("uint8"))