Video editing with Python
fixed resize bug with PIL. Added "loop" effect. Fixed save_frame. Added GIF export.
Zulko166a34d3ca2b
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex c00cc739..7a0fa8fe 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -25,7 +25,7 @@ import moviepy.video.io.ffmpeg_tools as ffmpeg_toolsfrom moviepy.video.tools.drawing import blitfrom moviepy.Clip import Clip-+from moviepy.conf import FFMPEG_BINARY@@ -85,10 +85,10 @@ class VideoClip(Clip):alpha layer of the picture."""im = self.get_frame(t)- if savemask:+ if savemask and self.mask is not None:mask = 255 * self.mask.get_frame(t)im = np.dstack([im, mask]).astype('uint8')- write_image(filename, im)+ ffmpeg_writer.write_image(filename, im)@requires_durationdef to_directory(self, foldername, fps, transparent=True,@@ -320,6 +320,86 @@ class VideoClip(Clip):pos = map(int, pos)return blit(img, picture, pos, mask=mask, ismask=self.ismask)++++ def to_gif(self, filename, fps=None, program= 'ImageMagick',+ opt="OptimizeTransparency", fuzz=1, verbose=True,+ loop=0, dispose=False):+ """+ Converts a VideoClip into an animated GIF using ImageMagick or+ ffmpeg.+ :param clip: the VideoClip to be converted.+ :param filename: name of the gif, like 'myAnimation.gif'+ :param fps: number of frames per second (see note below). If it+ isn't provided, then the function will look for the clip's+ ``fps`` attribute (VideoFileClip, for instance, have one).+ :param program: software to use for the conversion, either+ 'ImageMagick' or 'ffmpeg'.+ :param opt: (ImageMagick only) optimalization to apply, either+ 'optimizeplus' or 'OptimizeTransparency'.+ :param fuzz: (ImageMagick only) Compresses the GIF by considering+ that the colors that are less than fuzz% different are in fact+ the same.+++ *Note:* The gif will be playing the clip in real time (you can+ only change the frame rate). If you want the gif to be slower+ than the clip you will write++ >>> # slow down clip 50% and make it a gif+ >>> myClip.speedx(0.5).++ """++ def verboseprint(s):+ if verbose: print "MoviePy: " + s++ if fps is None:+ fps = self.fps++ fileName, fileExtension = os.path.splitext(filename)+ tt = np.arange(0,self.duration, 1.0/fps)+ tempfiles = []++ verboseprint( "Generating GIF frames" )++ for i, t in enumerate(tt):++ name = "%s_TEMP%04d.png"%(fileName,i+1)+ tempfiles.append(name)+ self.save_frame(name, t, savemask=True)++ delay = int(100.0/fps)++ if program == "ImageMagick":++ cmd = ("convert -delay %d"%delay ++ " -dispose %d"%(2 if dispose else 1)++ " -loop %d"%loop++ " `seq -f %s"%fileName +"_TEMP%04g.png"++ " 1 1 %d`"%len(tt) ++ " -coalesce -fuzz %02d"%fuzz + "%"++ " -layers %s %s"%(opt,filename))+ os.system(cmd)++ elif program == "ffmpeg":++ cmd = [FFMPEG_BINARY,'-y', '-f', 'image2',+ '-i', fileName+'_TEMP%04d.png',+ '-r',str(fps),+ filename]++ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE)+ proc.wait()+ print proc.stderr++ for f in tempfiles:+ os.remove(f)++ verboseprint('GIF generated !')#-----------------------------------------------------------------# F I L T E R I N G@@ -369,11 +449,12 @@ class VideoClip(Clip)::param constant_size: `False` for clips with moving image size."""if constant_size:- return self.set_mask(ColorClip(self.size, 1.0, ismask=True))+ mask = ColorClip(self.size, 1.0, ismask=True)+ return self.set_mask( mask.set_duration(self.duration))else:mask = VideoClip(ismask=True).set_get_frame(lambda t: np.ones(self.get_frame(t).shape))- return self.set_mask(mask)+ return self.set_mask(mask.set_duration(self.duration))def on_color(self, size=None, color=(0, 0, 0), pos=None, col_opacity=None):"""@@ -396,8 +477,11 @@ class VideoClip(Clip):if col_opacity:colorclip = colorclip.set_opacity(col_opacity)- return CompositeVideoClip([colorclip, self.set_pos(pos)],+ result = CompositeVideoClip([colorclip, self.set_pos(pos)],transparent=(col_opacity != None))+ if hasattr(self,'duration'):+ result.duration = self.duration+ return resultdef set_get_frame(self, gf):diff --git a/moviepy/video/compositing/concatenate.py b/moviepy/video/compositing/concatenate.pyindex 33e9cb01..b3fb3423 100644--- a/moviepy/video/compositing/concatenate.py+++ b/moviepy/video/compositing/concatenate.py@@ -67,7 +67,7 @@ def concatenate(clipslist, method = 'chain', transition=None,transparent=transparent)result.start_times = tt[:-1]- result.duration = tt[-1]+ result.start, result.duration, result.end = 0, tt[-1] , tt[-1]# Compute the mask if anydiff --git a/moviepy/video/fx/loop.py b/moviepy/video/fx/loop.pyindex 20dce02f..99594299 100644--- a/moviepy/video/fx/loop.py+++ b/moviepy/video/fx/loop.py@@ -6,9 +6,14 @@ from moviepy.decorators import (apply_to_mask,@requires_duration@apply_to_mask@apply_to_audio-def loop(self):- """- Returns a clip that plays the current clip in an infinite loop.- Ideal for clips coming from gifs.- """- return self.fl_time(lambda t: t % self.duration)+def loop(self, n=None):+ """+ Returns a clip that plays the current clip in an infinite loop.+ Ideal for clips coming from gifs.+ :param n: number of times the clip should be played. If `None` the+ the clip will loop indefinitely (i.e. with no set duration).+ """+ result = self.fl_time(lambda t: t % self.duration)+ if n:+ result.duration = n*self.duration+ return resultdiff --git a/moviepy/video/fx/resize.py b/moviepy/video/fx/resize.pyindex 27f6a392..e75564e9 100644--- a/moviepy/video/fx/resize.py+++ b/moviepy/video/fx/resize.py@@ -2,27 +2,37 @@resize_possible = Truetry:+import cv2resizer = lambda pic, newsize : cv2.resize(pic.astype('uint8'),tuple(map(int, newsize)),interpolation=cv2.INTER_AREA)-except:++except ImportError:+try:+import Image+ import numpy as npdef resizer(pic, newsize):newsize = map(int, newsize)[::-1]shape = pic.shape- newshape = (newsize[0],newsize[2],shape[1])+ newshape = (newsize[0],newsize[1],shape[2])pilim = Image.fromarray(pic)- resized_pil = pilim.resize(newsize, Image.ANTIALIAS)+ resized_pil = pilim.resize(newsize[::-1], Image.ANTIALIAS)arr = np.fromstring(resized_pil.tostring(), dtype='uint8')return arr.reshape(newshape)- except:++ except ImportError:+try:+import scipy.misc.imresize as imresizeresizer = lambda pic, newsize : imresize(pic,map(int, newsize[::-1]))- except:++ except ImportError:+resize_possible = False@@ -88,5 +98,5 @@ def resize(clip, newsize=None, height=None, width=None):if not resize_possible:doc = resize.__doc__def resize(clip, newsize=None, height=None, width=None):- raise IOError("fx resize needs OpenCV or Scipy or PIL")+ raise ImportError("fx resize needs OpenCV or Scipy or PIL")resize.__doc__ = docdiff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.pyindex 2466b40d..5065d43c 100644--- a/moviepy/video/io/ffmpeg_writer.py+++ b/moviepy/video/io/ffmpeg_writer.py@@ -95,7 +95,15 @@ def ffmpeg_write(clip, filename, fps, codec="libx264", bitrate=None,def write_image(filename, image):- pix_fmt = "rgba" if (image.shape[2] == 4) else "rgb24"- vf = FFMPEG_VideoWriter(filename, pix_fmt='rgba')- vf.writer_frame(image)- vf.close()+ """ Writes an image (HxWx3 or HxWx4 numpy array) to a file, using+ ffmpeg. """+ proc = sp.Popen([ "ffmpeg", '-y',+ '-s', "%dx%d"%(image.shape[:2][::-1]),+ "-f", 'rawvideo',+ '-pix_fmt', "rgba" if (image.shape[2] == 4) else "rgb24",+ '-i','-', filename],+ stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)+ image.tofile(proc.stdin)+ proc.stdin.close()+ proc.wait()+ del procdiff --git a/moviepy/video/io/imageMagick_tools.py b/moviepy/video/io/imageMagick_tools.pyindex c5a9732e..f9bd3674 100644--- a/moviepy/video/io/imageMagick_tools.py+++ b/moviepy/video/io/imageMagick_tools.py@@ -1,3 +1,7 @@+import os+import subprocess+from moviepy.conf import FFMPEG_BINARY+@subprocess_calldef gif_to_directory(gif_file,dirName=None):"""