Video editing with Python
unified clip.write_gif and clip.write_gif2. Now no temp files is the default.
Zulko742e4eacdfaf
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex f678d2b3..4893aed9 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -21,6 +21,7 @@ import moviepy.audio.io as aiofrom .io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_videofrom .io.ffmpeg_reader import ffmpeg_read_imagefrom .io.ffmpeg_tools import ffmpeg_merge_video_audio+from .io.gif_writers import write_gif, write_gif_with_tempfilesfrom .tools.drawing import blit@@ -387,7 +388,7 @@ class VideoClip(Clip):@requires_durationdef write_gif(self, filename, fps=None, program= 'ImageMagick',opt="OptimizeTransparency", fuzz=1, verbose=True,- loop=0, dispose=False):+ loop=0, dispose=False, colors=None, tempfiles=False):""" Write the VideoClip to a GIF file.Converts a VideoClip into an animated GIF using ImageMagick@@ -430,203 +431,15 @@ class VideoClip(Clip):>>> myClip.speedx(0.5).to_gif('myClip.gif')"""-- if fps is None:- fps = self.fps-- fileName, fileExtension = os.path.splitext(filename)- tt = np.arange(0,self.duration, 1.0/fps)-- tempfiles = []-- verbose_print(verbose, "\nMoviePy: building GIF file %s\n"%filename- +40*"-"+"\n")-- verbose_print(verbose, "Generating GIF frames.\n")-- total = int(self.duration*fps)+1- for i, t in tqdm(enumerate(tt), total=total):-- name = "%s_GIFTEMP%04d.png"%(fileName, i+1)- tempfiles.append(name)- self.save_frame(name, t, savemask=True)-- verbose_print(verbose, "Done generating GIF frames.\n")-- delay = int(100.0/fps)-- if program == "ImageMagick":-- cmd = [IMAGEMAGICK_BINARY,- '-delay' , '%d'%delay,- "-dispose" ,"%d"%(2 if dispose else 1),- "-loop" , "%d"%loop,- "%s_GIFTEMP*.png"%fileName,- "-coalesce",- "-fuzz", "%02d"%fuzz + "%",- "-layers", "%s"%opt,- filename]-- elif program == "ffmpeg":-- cmd = [FFMPEG_BINARY, '-y',- '-f', 'image2', '-r',str(fps),- '-i', fileName+'_GIFTEMP%04d.png',- '-r',str(fps),- filename]-- try:- subprocess_call( cmd, verbose = verbose )-- except IOError as err:-- error = ("MoviePy Error: creation of %s failed because "- "of the following error:\n\n%s.\n\n."%(filename, str(err)))-- if program == "ImageMagick":- error = error + ("This can be due to the fact that "- "ImageMagick is not installed on your computer, or "- "(for Windows users) that you didn't specify the "- "path to the ImageMagick binary in file conf.py." )-- raise IOError(error)-- for f in tempfiles:- os.remove(f)---- @requires_duration- def write_gif2(self, filename, fps=None, program= 'ImageMagick',- opt="OptimizeTransparency", fuzz=1, verbose=True,- loop=0, dispose=False):- """ Write the VideoClip to a GIF file, without temporary files.-- Converts a VideoClip into an animated GIF using ImageMagick- or ffmpeg.--- Parameters- ------------- filename- Name of the resulting gif file.-- 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).-- program- Software to use for the conversion, either 'ImageMagick' or- 'ffmpeg'.-- opt- (ImageMagick only) optimalization to apply, either- 'optimizeplus' or 'OptimizeTransparency'.-- fuzz- (ImageMagick only) Compresses the GIF by considering that- the colors that are less than fuzz% different are in fact- the same.--- Notes- ------- The gif will be playing the clip in real time (you can- only change the frame rate). If you want the gif to be played- slower than the clip you will use ::-- >>> # slow down clip 50% and make it a gif- >>> myClip.speedx(0.5).write_gif('myClip.gif')-- """- #- # We use processes chained with pipes.- #- # if program == 'ffmpeg'- # frames --ffmpeg--> gif- #- # if program == 'ImageMagick' and optimize == (None, False)- # frames --ffmpeg--> bmp frames --ImageMagick--> gif- #- #- # if program == 'ImageMagick' and optimize != (None, False)- # frames -ffmpeg-> bmp frames -ImagMag-> gif -ImagMag-> better gif- #-- if fps is None:- fps=self.fps- delay= 100.0/fps-- cmd1 = [FFMPEG_BINARY, '-y', '-loglevel', 'error',- '-f', 'rawvideo',- '-vcodec','rawvideo', '-r', "%.02f"%fps,- '-s', "%dx%d"%(self.w, self.h), '-pix_fmt', 'rgb24',- '-i', '-']-- if program == "ffmpeg":- proc1 = sp.Popen(cmd1+['-r', "%.02f"%fps, filename],- stdin=sp.PIPE, stdout=DEVNULL)+ if tempfiles:+ write_gif_with_tempfiles(self, filename, fps=fps,+ program= program, opt=opt, fuzz=fuzz, verbose=verbose,+ loop=loop, dispose= dispose, colors=colors)else:- proc1 = sp.Popen(cmd1+['-f', 'image2pipe',- '-vcodec', 'bmp', '-'],- stdin=sp.PIPE, stdout=sp.PIPE)-- if program == 'ImageMagick':-- cmd2 = [IMAGEMAGICK_BINARY, '-delay', "%.02f"%(delay),- "-dispose" ,"%d"%(2 if dispose else 1),- '-loop', '%d'%loop, '-', '-coalesce']-- if (opt in [False, None]):- proc2 = sp.Popen(cmd2+[filename], stdin=proc1.stdout)-- else:- proc2 = sp.Popen(cmd2+['gif:-'] , stdin=proc1.stdout,- stdout=sp.PIPE)-- if opt:-- cmd3 = [IMAGEMAGICK_BINARY, '-', '-layers', opt,- '-fuzz', '%d'%fuzz+'%',filename]- proc3 = sp.Popen(cmd3, stdin=proc2.stdout)-- # We send all the frames to the first process- verbose_print(verbose, "\nMoviePy: building GIF file %s\n"%filename- +40*"-"+"\n")- verbose_print(verbose, "Generating GIF frames...\n")-- try:-- for frame in self.iter_frames(fps=fps, progress_bar=True):- proc1.stdin.write(frame.tostring())- verbose_print(verbose, "Done.\n")-- except IOError as err:-- error = ("MoviePy Error: creation of %s failed because "- "of the following error:\n\n%s.\n\n."%(filename, str(err)))-- if program == "ImageMagick":- error = error + ("This can be due to the fact that "- "ImageMagick is not installed on your computer, or "- "(for Windows users) that you didn't specify the "- "path to the ImageMagick binary in file conf.py." )-- raise IOError(error)- verbose_print(verbose, "Writing GIF... ")- proc1.stdin.close()- proc1.wait()- if program == 'ImageMagick':- proc2.wait()- if opt:- proc3.wait()- verbose_print(verbose, 'Done. Your GIF is ready !')--+ write_gif(self, filename, fps=fps, program= program,+ opt=opt, fuzz=fuzz, verbose=verbose, loop=loop,+ dispose= dispose, colors=colors)#-----------------------------------------------------------------# F I L T E R I N Gdiff --git a/moviepy/video/io/gif_writers.py b/moviepy/video/io/gif_writers.pynew file mode 100644index 00000000..0218cbab--- /dev/null+++ b/moviepy/video/io/gif_writers.py@@ -0,0 +1,220 @@+import os+import subprocess as sp+from tqdm import tqdm+from moviepy.conf import FFMPEG_BINARY, IMAGEMAGICK_BINARY+from moviepy.decorators import requires_duration+from moviepy.tools import verbose_print, subprocess_call+import numpy as np+++@requires_duration+def write_gif_with_tempfiles(clip, filename, fps=None, program= 'ImageMagick',+ opt="OptimizeTransparency", fuzz=1, verbose=True,+ loop=0, dispose=False, colors=None, tempfiles=False):+ """ Write the VideoClip to a GIF file.+++ Converts a VideoClip into an animated GIF using ImageMagick+ or ffmpeg. Does the same as write_gif (see this one for more+ docstring), but writes every frame to a file instead of passing+ them in the RAM. Useful on computers with little RAM.++ """++ if fps is None:+ fps = clip.fps++ fileName, fileExtension = os.path.splitext(filename)+ tt = np.arange(0,clip.duration, 1.0/fps)++ tempfiles = []++ verbose_print(verbose, "\nMoviePy: building GIF file %s\n"%filename+ +40*"-"+"\n")++ verbose_print(verbose, "Generating GIF frames.\n")++ total = int(clip.duration*fps)+1+ for i, t in tqdm(enumerate(tt), total=total):++ name = "%s_GIFTEMP%04d.png"%(fileName, i+1)+ tempfiles.append(name)+ clip.save_frame(name, t, savemask=True)++ verbose_print(verbose, "Done generating GIF frames.\n")++ delay = int(100.0/fps)++ if program == "ImageMagick":++ cmd = [IMAGEMAGICK_BINARY,+ '-delay' , '%d'%delay,+ "-dispose" ,"%d"%(2 if dispose else 1),+ "-loop" , "%d"%loop,+ "%s_GIFTEMP*.png"%fileName,+ "-coalesce",+ "-layers", "%s"%opt,+ "-fuzz", "%02d"%fuzz + "%",+ ]+(["-colors", "%d"%colors] if colors is not None else [])+[+ filename]++ elif program == "ffmpeg":++ cmd = [FFMPEG_BINARY, '-y',+ '-f', 'image2', '-r',str(fps),+ '-i', fileName+'_GIFTEMP%04d.png',+ '-r',str(fps),+ filename]++ try:+ subprocess_call( cmd, verbose = verbose )++ except IOError as err:++ error = ("MoviePy Error: creation of %s failed because "+ "of the following error:\n\n%s.\n\n."%(filename, str(err)))++ if program == "ImageMagick":+ error = error + ("This can be due to the fact that "+ "ImageMagick is not installed on your computer, or "+ "(for Windows users) that you didn't specify the "+ "path to the ImageMagick binary in file conf.py." )++ raise IOError(error)++ for f in tempfiles:+ os.remove(f)++++@requires_duration+def write_gif(clip, filename, fps=None, program= 'ImageMagick',+ opt="OptimizeTransparency", fuzz=1, verbose=True,+ loop=0, dispose=False, colors=None):+ """ Write the VideoClip to a GIF file, without temporary files.++ Converts a VideoClip into an animated GIF using ImageMagick+ or ffmpeg.+++ Parameters+ -----------++ filename+ Name of the resulting gif file.++ 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).++ program+ Software to use for the conversion, either 'ImageMagick' or+ 'ffmpeg'.++ opt+ (ImageMagick only) optimalization to apply, either+ 'optimizeplus' or 'OptimizeTransparency'.++ fuzz+ (ImageMagick only) Compresses the GIF by considering that+ the colors that are less than fuzz% different are in fact+ the same.+++ Notes+ -----++ The gif will be playing the clip in real time (you can+ only change the frame rate). If you want the gif to be played+ slower than the clip you will use ::++ >>> # slow down clip 50% and make it a gif+ >>> myClip.speedx(0.5).write_gif('myClip.gif')++ """++ #+ # We use processes chained with pipes.+ #+ # if program == 'ffmpeg'+ # frames --ffmpeg--> gif+ #+ # if program == 'ImageMagick' and optimize == (None, False)+ # frames --ffmpeg--> bmp frames --ImageMagick--> gif+ #+ #+ # if program == 'ImageMagick' and optimize != (None, False)+ # frames -ffmpeg-> bmp frames -ImagMag-> gif -ImagMag-> better gif+ #++ if fps is None:+ fps=clip.fps+ delay= 100.0/fps++ cmd1 = [FFMPEG_BINARY, '-y', '-loglevel', 'error',+ '-f', 'rawvideo',+ '-vcodec','rawvideo', '-r', "%.02f"%fps,+ '-s', "%dx%d"%(clip.w, clip.h), '-pix_fmt', 'rgb24',+ '-i', '-']++ if program == "ffmpeg":+ proc1 = sp.Popen(cmd1+['-r', "%.02f"%fps, filename],+ stdin=sp.PIPE, stdout=DEVNULL)+ else:+ proc1 = sp.Popen(cmd1+['-f', 'image2pipe',+ '-vcodec', 'bmp', '-'],+ stdin=sp.PIPE, stdout=sp.PIPE)++ if program == 'ImageMagick':++ cmd2 = [IMAGEMAGICK_BINARY, '-delay', "%.02f"%(delay),+ "-dispose" ,"%d"%(2 if dispose else 1),+ '-loop', '%d'%loop, '-', '-coalesce']++ if (opt in [False, None]):+ proc2 = sp.Popen(cmd2+[filename], stdin=proc1.stdout)++ else:+ proc2 = sp.Popen(cmd2+['gif:-'] , stdin=proc1.stdout,+ stdout=sp.PIPE)++ if opt:++ cmd3 = [IMAGEMAGICK_BINARY, '-', '-layers', opt,+ '-fuzz', '%d'%fuzz+'%'+ ]+(["-colors", "%d"%colors] if colors is not None else [])+[+ filename]+ proc3 = sp.Popen(cmd3, stdin=proc2.stdout)++ # We send all the frames to the first process+ verbose_print(verbose, "\nMoviePy: building GIF file %s\n"%filename+ +40*"-"+"\n")+ verbose_print(verbose, "Generating GIF frames...\n")++ try:++ for frame in clip.iter_frames(fps=fps, progress_bar=True):+ proc1.stdin.write(frame.tostring())+ verbose_print(verbose, "Done.\n")++ except IOError as err:++ error = ("MoviePy Error: creation of %s failed because "+ "of the following error:\n\n%s.\n\n."%(filename, str(err)))++ if program == "ImageMagick":+ error = error + ("This can be due to the fact that "+ "ImageMagick is not installed on your computer, or "+ "(for Windows users) that you didn't specify the "+ "path to the ImageMagick binary in file conf.py." )++ raise IOError(error)+ verbose_print(verbose, "Writing GIF... ")+ proc1.stdin.close()+ proc1.wait()+ if program == 'ImageMagick':+ proc2.wait()+ if opt:+ proc3.wait()+ verbose_print(verbose, 'Done. Your GIF is ready !')\ No newline at end of filediff --git a/moviepy/video/tools/cuts.py b/moviepy/video/tools/cuts.pynew file mode 100644index 00000000..7bd23c51--- /dev/null+++ b/moviepy/video/tools/cuts.py@@ -0,0 +1,14 @@+""" This module contains everything that can help automatize+the cuts in MoviePy """++import numpy as np+++def find_period(clip,fps=None,tmin=.3):+ if fps is None:+ fps=clip.fps+ frame = lambda t: clip.get_frame(t).flatten()+ tt = np.arange(tmin,clip.duration,1.0/ fps)[1:]+ ref = frame(0)+ corrs = [ np.corrcoef(ref, frame(t))[0,1] for t in tt]+ return tt[np.argmax(corrs)]\ No newline at end of file