Video editing with Python
Fixes transparency bug (not 100% tested). Also added imageio gif backend.
Zulkob2bf7156279c
diff --git a/moviepy/tools.py b/moviepy/tools.pyindex a570ecba..686fdf63 100644--- a/moviepy/tools.py+++ b/moviepy/tools.py@@ -29,7 +29,7 @@ def verbose_print(verbose, s):def subprocess_call(cmd, verbose=True, errorprint=True):""" Executes the given subprocess command."""- verbose_print(verbose, "\nMoviePy Running:\n>>> "+ " ".join(cmd))+ verbose_print(verbose, "\n[MoviePy] Running:\n>>> "+ " ".join(cmd))popen_params = {"stdout": DEVNULL,"stderr": sp.PIPE,@@ -44,7 +44,7 @@ def subprocess_call(cmd, verbose=True, errorprint=True):proc.stderr.close()if proc.returncode:- verbose_print(errorprint, "\nMoviePy: This command returned an error !")+ verbose_print(errorprint, "\n[MoviePy] This command returned an error !")raise IOError(err.decode('utf8'))else:verbose_print(verbose, "\n... command successful.\n")diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex fded73c0..412d0816 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -18,7 +18,9 @@ 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_tempfiles+from .io.gif_writers import (write_gif,+ write_gif_with_tempfiles,+ write_gif_with_image_io)from .tools.drawing import blitfrom ..Clip import Clipfrom ..config import get_setting@@ -447,8 +449,11 @@ class VideoClip(Clip):>>> myClip.speedx(0.5).to_gif('myClip.gif')"""+ if program == 'imageio':+ write_gif_with_image_io(self, filename, fps=fps, opt=opt, loop=loop,+ verbose=verbose, colors=colors)- if tempfiles:+ elif tempfiles:write_gif_with_tempfiles(self, filename, fps=fps,program=program, opt=opt, fuzz=fuzz,verbose=verbose,@@ -613,13 +618,13 @@ class VideoClip(Clip):colorclip = ColorClip(size, color)if col_opacity is not None:- colorclip = colorclip.set_opacity(col_opacity)-- if self.duration is not None:- colorclip = colorclip.set_duration(self.duration)-- result = CompositeVideoClip([colorclip, self.set_pos(pos)],- transparent=(col_opacity is not None))+ colorclip = (ColorClip(size, color, duration=elf.duration)+ .set_opacity(col_opacity))+ result = CompositeVideoClip([colorclip, self.set_pos(pos)])+ else:+ result = CompositeVideoClip([self.set_pos(pos)],+ size=size,+ bg_color=color)if (isinstance(self, ImageClip) and (not hasattr(pos, "__call__"))and ((self.mask is None) or isinstance(self.mask, ImageClip))):@@ -875,9 +880,9 @@ class ImageClip(VideoClip):def __init__(self, img, ismask=False, transparent=True,- fromalpha=False):+ fromalpha=False, duration=None):- VideoClip.__init__(self, ismask=ismask)+ VideoClip.__init__(self, ismask=ismask, duration=duration)if isinstance(img, str):img = ffmpeg_read_image(img, with_mask=transparent)@@ -993,11 +998,11 @@ class ColorClip(ImageClip):"""- def __init__(self, size, col=(0, 0, 0), ismask=False):+ def __init__(self, size, col=(0, 0, 0), ismask=False, duration=None):w, h = sizeshape = (h, w) if np.isscalar(col) else (h, w, len(col))ImageClip.__init__(self, np.tile(col, w * h).reshape(shape),- ismask=ismask)+ ismask=ismask, duration=duration)class TextClip(ImageClip):diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.pyindex 85b2b154..e3a6d43a 100644--- a/moviepy/video/compositing/CompositeVideoClip.py+++ b/moviepy/video/compositing/CompositeVideoClip.py@@ -29,35 +29,48 @@ class CompositeVideoClip(VideoClip):attribute set, then the duration of the composite video clipis computed automatically- transparent- If False, the clips are overlaid on a surface- of the color `bg_color`. If True, the clips are overlaid on- a transparent surface, so that all pixels that are transparent- for all clips will be transparent in the composite clip. More- precisely, the mask of the composite clip is then the composite- of the masks of the different clips. Only use `transparent=True`- when you intend to use your composite clip as part of another- composite clip and you care about its transparency.-+ bg_color+ Color for the unmasked and unfilled regions. Set to None for these+ regions to be transparent (will be slower).++ If all clips with a fps attribute have the same fps, it becomes the fps of+ the result.+"""- def __init__(self, clips, size=None, bg_color=None, transparent=False,+ def __init__(self, clips, size=None, bg_color=None, use_bgclip=False,ismask=False):-+if size is None:size = clips[0].sizeif bg_color is None:bg_color = 0.0 if ismask else (0, 0, 0)++ if use_bgclip and (clips[0].mask is None):+ transparent = False+ else:+ transparent = (bg_color is None)+ fps_list = list(set([c.fps for c in clips if hasattr(c,'fps')]))+ if len(fps_list)==1:+ self.fps= fps_list[0]+VideoClip.__init__(self)self.size = sizeself.ismask = ismaskself.clips = clips- self.transparent = transparentself.bg_color = bg_color- self.bg = ColorClip(size, col=self.bg_color).get_frame(0)++ if use_bgclip:+ self.bg = clips[0]+ self.clips = clips[1:]+ else:+ self.clips = clips+ self.bg = ColorClip(size, col=self.bg_color)++# compute durationends = [c.end for c in self.clips]@@ -70,19 +83,19 @@ class CompositeVideoClip(VideoClip):if len(audioclips) > 0:self.audio = CompositeAudioClip(audioclips)- # compute mask+ # compute mask if necessaryif transparent:maskclips = [c.mask.set_pos(c.pos) for c in self.clipsif c.mask is not None]if maskclips != []:- self.mask = CompositeVideoClip(maskclips,self.size,- transparent=False, ismask=True)+ self.mask = CompositeVideoClip(maskclips,self.size, ismask=True,+ bg_color=0)def make_frame(t):""" The clips playing at time `t` are blitted over oneanother. """- f = self.bg+ f = self.bg.get_frame(t)for c in self.playing_clips(t):f = c.blit_on(f, t)return f@@ -97,11 +110,28 @@ class CompositeVideoClip(VideoClip):def clips_array(array, rows_widths=None, cols_widths=None,- transparent = False, bg_color = None):+ bg_color = None):++ """++ rows_widths+ widths of the different rows in pixels. If None, is set automatically.++ cols_widths+ widths of the different colums in pixels. If None, is set automatically.++ cols_widths++ bg_color+ Fill color for the masked and unfilled regions. Set to None for these+ regions to be transparent (will be slower).++ """array = np.array(array)sizes_array = np.array([[c.size for c in line] for line in array])+ # find row width and col_widths automatically if not providedif rows_widths is None:rows_widths = sizes_array[:,:,1].max(axis=1)if cols_widths is None:@@ -117,14 +147,12 @@ def clips_array(array, rows_widths=None, cols_widths=None,if (w < cw) or (h < rw):clip = (CompositeVideoClip([clip.set_pos('center')],size = (cw,rw),- transparent = transparent,bg_color = bg_color).set_duration(clip.duration))array[i,j] = clip.set_pos((x,y))return CompositeVideoClip(array.flatten(), size = (xx[-1],yy[-1]),- transparent=transparent,bg_color = bg_color)diff --git a/moviepy/video/compositing/concatenate.py b/moviepy/video/compositing/concatenate.pyindex 22fe1370..2ac37959 100644--- a/moviepy/video/compositing/concatenate.py+++ b/moviepy/video/compositing/concatenate.py@@ -1,39 +1,43 @@import numpy as npfrom moviepy.tools import deprecated_version_of-from moviepy.video.VideoClip import VideoClip+from moviepy.video.VideoClip import VideoClip, ColorClipfrom moviepy.video.compositing.CompositeVideoClip import CompositeVideoClipfrom moviepy.audio.AudioClip import CompositeAudioClipfrom moviepy.video.compositing.on_color import on_color-def concatenate_videoclips(clipslist, method="chain", transition=None, bg_color=(0, 0, 0),- transparent=False, ismask=False, padding = 0):+def concatenate_videoclips(clips, method="chain", transition=None,+ bg_color=None, ismask=False, padding = 0):""" Concatenates several video clipsReturns a video clip made by clip by concatenating several video clips.(Concatenated means that they will be played one after another).- There are two methods: method="chain" will produce a clip that simply outputs- the frames of the succesive clips, without any correction if they are- not of the same size of anything.-- With method="compose", if the clips do not have the same- resolution, the final resolution will be such that no clip has- to be resized.- As a consequence the final clip has the height of the highest- clip and the width of the widest clip of the list. All the- clips with smaller dimensions will appear centered. The border- will be transparent if mask=True, else it will be of the- color specified by ``bg_color``.-- Returns a VideoClip instance if all clips have the same size and- there is no transition, else a composite clip.-+ There are two methods:++ - method="chain": will produce a clip that simply outputs+ the frames of the succesive clips, without any correction if they are+ not of the same size of anything. If none of the clips have masks the+ resulting clip has no mask, else the mask is a concatenation of masks+ (using completely opaque for clips that don't have masks, obviously).++ - method="compose", if the clips do not have the same+ resolution, the final resolution will be such that no clip has+ to be resized.+ As a consequence the final clip has the height of the highest+ clip and the width of the widest clip of the list. All the+ clips with smaller dimensions will appear centered. The border+ will be transparent if mask=True, else it will be of the+ color specified by ``bg_color``.++ If all clips with a fps attribute have the same fps, it becomes the fps of+ the result.+Parameters------------ clipslist+ clipsA list of video clips which must all have their ``duration``attributes set.@@ -41,33 +45,30 @@ def concatenate_videoclips(clipslist, method="chain", transition=None, bg_color="chain" or "compose": see above.transition- A clip that will be played between each two clips of the list.+ A clip that will be played between each two clips of the list.bg_color- Color of the background, if any.-- transparent- If True, the resulting clip's mask will be the concatenation of- the masks of the clips in the list. If the clips do not have the- same resolution, the border around the smaller clips will be- transparent.-+ Only for method='compose'. Color of the background.+ Set to None for a transparent clip+padding- Duration during two consecutive clips. If negative, a clip will- play at the same time as the clip it follows. A non-null- padding automatically sets the method to `compose`.+ Only for method='compose'. Duration during two consecutive clips.+ Note that for negative padding, a clip will partly play at the same+ time as the clip it follows (negative padding is cool for clips who fade+ in on one another). A non-null padding automatically sets the method to+ `compose`."""if transition is not None:- l = [[v, transition] for v in clipslist[:-1]]- clipslist = reduce(lambda x, y: x + y, l) + [clipslist[-1]]+ l = [[v, transition] for v in clips[:-1]]+ clips = reduce(lambda x, y: x + y, l) + [clips[-1]]transition = None- tt = np.cumsum([0] + [c.duration for c in clipslist])+ tt = np.cumsum([0] + [c.duration for c in clips])- sizes = [v.size for v in clipslist]+ sizes = [v.size for v in clips]w = max([r[0] for r in sizes])@@ -78,30 +79,36 @@ def concatenate_videoclips(clipslist, method="chain", transition=None, bg_color=if method == "chain":def make_frame(t):i = max([i for i, e in enumerate(tt) if e <= t])- return clipslist[i].get_frame(t - tt[i])+ return clips[i].get_frame(t - tt[i])result = VideoClip(ismask = ismask, make_frame = make_frame)- if transparent:- clips_w_masks = [(c.add_mask() if c.mask is None else c) for c in clips]- masks = [c.mask for c in clips_w_masks]- result.mask = concatenate_videoclips(masks, method="chain", ismask=True)+ if any([c.mask is not None for c in clips]):+ masks = [c.mask if (c.mask is not None) else+ ColorClip([1,1], col=1, ismask=True, duration=c.duration)+ #ColorClip(c.size, col=1, ismask=True).set_duration(c.duration)+ for c in clips]+ result.mask = concatenate_videoclips(masks, method="chain", ismask=True)elif method == "compose":result = CompositeVideoClip( [c.set_start(t).set_pos('center')- for (c, t) in zip(clipslist, tt)],- size = (w, h), bg_color=bg_color, ismask=ismask,- transparent=transparent )+ for (c, t) in zip(clips, tt)],+ size = (w, h), bg_color=bg_color, ismask=ismask)result.tt = tt- result.clipslist = clipslist+ result.clips = clipsresult.start_times = tt[:-1]result.start, result.duration, result.end = 0, tt[-1] , tt[-1]- audio_t = [(c.audio,t) for c,t in zip(clipslist,tt) if c.audio is not None]+ audio_t = [(c.audio,t) for c,t in zip(clips,tt) if c.audio is not None]if len(audio_t)>0:result.audio = CompositeAudioClip([a.set_start(t)for a,t in audio_t])++ fps_list = list(set([c.fps for c in clips if hasattr(c,'fps')]))+ if len(fps_list)==1:+ result.fps= fps_list[0]+return resultdiff --git a/moviepy/video/io/gif_writers.py b/moviepy/video/io/gif_writers.pyindex 1fb49038..b82a1d3c 100644--- a/moviepy/video/io/gif_writers.py+++ b/moviepy/video/io/gif_writers.py@@ -11,12 +11,21 @@ try:except ImportError:DEVNULL = open(os.devnull, 'wb')+try:+ import imageio+ IMAGEIO_FOUND = True+except ImportError:+ IMAGEIO_FOUND = False++++@requires_duration@use_clip_fps_by_defaultdef write_gif_with_tempfiles(clip, filename, fps=None, program= 'ImageMagick',opt="OptimizeTransparency", fuzz=1, verbose=True,- loop=0, dispose=False, colors=None, tempfiles=False):+ loop=0, dispose=True, colors=None, tempfiles=False):""" Write the VideoClip to a GIF file.@@ -42,7 +51,7 @@ def write_gif_with_tempfiles(clip, filename, fps=None, program= 'ImageMagick',name = "%s_GIFTEMP%04d.png"%(fileName, i+1)tempfiles.append(name)- clip.save_frame(name, t, savemask=True)+ clip.save_frame(name, t, withmask=True)delay = int(100.0/fps)@@ -92,8 +101,8 @@ def write_gif_with_tempfiles(clip, filename, fps=None, program= 'ImageMagick',@requires_duration@use_clip_fps_by_defaultdef write_gif(clip, filename, fps=None, program= 'ImageMagick',- opt="OptimizeTransparency", fuzz=1, verbose=True,- loop=0, dispose=False, colors=None):+ opt="OptimizeTransparency", fuzz=1, verbose=True, withmask=True,+ loop=0, dispose=True, colors=None):""" Write the VideoClip to a GIF file, without temporary files.Converts a VideoClip into an animated GIF using ImageMagick@@ -153,10 +162,14 @@ def write_gif(clip, filename, fps=None, program= 'ImageMagick',delay= 100.0/fps+ if clip.mask is None:+ withmask = False+cmd1 = [get_setting("FFMPEG_BINARY"), '-y', '-loglevel', 'error','-f', 'rawvideo','-vcodec','rawvideo', '-r', "%.02f"%fps,- '-s', "%dx%d"%(clip.w, clip.h), '-pix_fmt', 'rgb24',+ '-s', "%dx%d"%(clip.w, clip.h),+ '-pix_fmt', ('rgba' if withmask else 'rgb24'),'-i', '-']popen_params = {"stdout": DEVNULL,@@ -170,14 +183,14 @@ def write_gif(clip, filename, fps=None, program= 'ImageMagick',popen_params["stdin"] = sp.PIPEpopen_params["stdout"] = DEVNULL- proc1 = sp.Popen(cmd1+['-r', "%.02f"%fps, filename], **popen_params)+ proc1 = sp.Popen(cmd1+[ '-pix_fmt', ('rgba' if withmask else 'rgb24'),+ '-r', "%.02f"%fps, filename], **popen_params)else:popen_params["stdin"] = sp.PIPEpopen_params["stdout"] = sp.PIPE- proc1 = sp.Popen(cmd1+['-f', 'image2pipe',- '-vcodec', 'bmp', '-'],+ proc1 = sp.Popen(cmd1+ ['-f', 'image2pipe', '-vcodec', 'bmp', '-'],**popen_params)if program == 'ImageMagick':@@ -213,7 +226,11 @@ def write_gif(clip, filename, fps=None, program= 'ImageMagick',try:- for frame in clip.iter_frames(fps=fps, progress_bar=True):+ for t,frame in clip.iter_frames(fps=fps, progress_bar=True,+ with_times=True, dtype="uint8"):+ if withmask:+ mask = 255 * clip.mask.get_frame(t)+ frame = np.dstack([frame, mask]).astype('uint8')proc1.stdin.write(frame.tostring())except IOError as err:@@ -236,4 +253,39 @@ def write_gif(clip, filename, fps=None, program= 'ImageMagick',proc2.wait()if opt:proc3.wait()- verbose_print(verbose, "[MoviePy] >>>> File %s is ready !"%filename)\ No newline at end of file+ verbose_print(verbose, "[MoviePy] >>>> File %s is ready !"%filename)+++def write_gif_with_image_io(clip, filename, fps=None, opt='wu', loop=0,+ colors=None, verbose=True):+ """+ Writes the gif with the Python library ImageIO (calls FreeImage).++ For the moment ImageIO is not installed with MoviePy. You need to install+ imageio (pip install imageio) to use this.++ Parameters+ -----------+ opt++ """++ if colors is None:+ colors=256++ if not IMAGEIO_FOUND:+ raise ImportError("Writing a gif with imageio requires ImageIO installed,"+ " with e.g. 'pip install imageio'")++ if fps is None:+ fps = clip.fps++ quantizer = 'wu' if opt!= 'nq' else 'nq'+ writer = imageio.save(filename, duration=1.0/fps,+ quantizer=quantizer, palettesize=colors)++ verbose_print(verbose, "\n[MoviePy] Building file %s with imageio\n"%filename)++ for frame in clip.iter_frames(fps=fps, progress_bar=True, dtype='uint8'):++ writer.append_data(frame)