Video editing with Python
added subtitles. other changes in gallery, videoclip, compositevideo
Valentindf5400672019
diff --git a/docs/gallery.rst b/docs/gallery.rstindex 6a43c18a..e358c54c 100644--- a/docs/gallery.rst+++ b/docs/gallery.rst@@ -67,19 +67,16 @@ If you liked it there is also this blog post which attempts to cut a video preciMoviePy online----------------- Rinconcam- ~~~~~~~~~~~-- Rincomcam (link) is a camera which films surfers on the Californian beach of Point Rincon. At the end of each day it cuts together a video and puts it online. Everything is entirely automatized with Python. MoviePy is used to add transitions, titles and music to the videos.----+Rinconcam+~~~~~~~~~~~+Rincomcam (link) is a camera which films surfers on the Californian beach of Point Rincon. At the end of each day it cuts together a video and puts it online. Everything is entirely automatized with Python. MoviePy is used to add transitions, titles and music to the videos.MoviePy in sciences and technology------------------------------------++Piano rolls transcription to sheet music~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex 8d8d67d7..5b0f02c4 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -6,7 +6,8 @@ main subclasses:"""import os-import subprocess+import subprocess as sp+import multiprocessingimport tempfilefrom copy import copy@@ -20,6 +21,7 @@ from moviepy.decorators import (apply_to_mask,requires_duration,outplace,add_mask_if_none)+from moviepy.tools import (subprocess_call, verbose_print,deprecated_version_of)@@ -33,6 +35,14 @@ from ..Clip import Clipfrom ..conf import FFMPEG_BINARY, IMAGEMAGICK_BINARY+try:+ from subprocess import DEVNULL # py3k+except ImportError:+ import os+ DEVNULL = open(os.devnull, 'wb')+++class VideoClip(Clip):"""Base class for video clips.@@ -86,7 +96,7 @@ class VideoClip(Clip):self.audio = Noneself.pos = lambda t: (0, 0)self.relative_pos = False- if get_frame:+ if get_frame is not None:self.get_frame = get_frameself.size =get_frame(0).shape[:2][::-1]self.ismask = ismask@@ -379,11 +389,9 @@ class VideoClip(Clip):return filenames--def write_gif(self, filename, fps=None, program= 'ImageMagick',- opt="OptimizeTransparency", fuzz=1, verbose=True,- loop=0, dispose=False):+ opt="OptimizeTransparency", fuzz=1, verbose=True,+ loop=0, dispose=False):""" Write the VideoClip to a GIF file.Converts a VideoClip into an animated GIF using ImageMagick@@ -423,7 +431,7 @@ class VideoClip(Clip):slower than the clip you will use ::>>> # slow down clip 50% and make it a gif- >>> myClip.speedx(0.5).write_gif('myClip.gif')+ >>> myClip.speedx(0.5).to_gif('myClip.gif')"""@@ -435,14 +443,14 @@ class VideoClip(Clip):tempfiles = []verbose_print(verbose, "\nMoviePy: building GIF file %s\n"%filename- +40*"-"+"\n")+ +40*"-"+"\n")verbose_print(verbose, "Generating GIF frames.\n")- total = int(self.duration/fps)+1+ total = int(self.duration*fps)+1for i, t in tqdm(enumerate(tt), total=total):- name = "%s_GIFTEMP%04d.png"%(fileName, i+1)+ name = "%s_GIFTEMP%04d.bmp"%(fileName, i+1)tempfiles.append(name)self.save_frame(name, t, savemask=True)@@ -465,13 +473,12 @@ class VideoClip(Clip):elif program == "ffmpeg":cmd = [FFMPEG_BINARY, '-y',- '-f', 'image2',- '-i', fileName+'_GIFTEMP%04d.png',+ '-f', 'image2', '-r',str(fps),+ '-i', fileName+'_GIFTEMP%04d.bmp','-r',str(fps),filename]try:-subprocess_call( cmd, verbose = verbose )except IOError as err:@@ -492,6 +499,128 @@ class VideoClip(Clip):+ 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++ cmd1 = [FFMPEG_BINARY, '-y', '-loglevel', 'error',+ '-f', 'rawvideo',+ '-vcodec','rawvideo', '-r', "%.02f"%fps,+ '-s', "%dx%d"%(self.w, self.h), '-pix_fmt', 'rgb24',+ '-i', '-']+ cmd1a = cmd1+['-r', "%.02f"%fps, filename]+ cmd1b = cmd1+['-f', 'image2pipe','-vcodec', 'bmp', '-']++ cmd2 = [IMAGEMAGICK_BINARY, '-', '-delay', "%d"%int(100.0/fps),+ '-loop', '%d'%loop]+ cmd2a = cmd2+[filename]+ cmd2b = cmd2+['gif:-']++ proc1 = (sp.Popen(cmd1a, stdin=sp.PIPE, stdout=DEVNULL) if (program =='ffmpeg')+ else sp.Popen(cmd1b, stdin=sp.PIPE, stdout=sp.PIPE))++ if program == 'ImageMagick':+ proc2 = (sp.Popen(cmd2a, stdin=proc1.stdout) if (opt in [False, None])+ else sp.Popen(cmd2b, 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")+ nframes = int(self.duration*fps)+1++ try:++ for frame in tqdm(self.iter_frames(fps=fps), total=nframes):+ 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 !')+++#-----------------------------------------------------------------# F I L T E R I N G@@ -1124,8 +1253,8 @@ class TextClip(ImageClip):""" Returns the list of all valid entries for the argument of``TextClip`` given (can be ``font``, ``color``, etc...) """- process = subprocess.Popen([IMAGEMAGICK_BINARY, '-list', arg],- stdout=subprocess.PIPE)+ process = sp.Popen([IMAGEMAGICK_BINARY, '-list', arg],+ stdout=sp.PIPE)result = process.communicate()[0]lines = result.splitlines()diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.pyindex 668a9011..6f899a3f 100644--- a/moviepy/video/compositing/CompositeVideoClip.py+++ b/moviepy/video/compositing/CompositeVideoClip.py@@ -10,22 +10,27 @@ class CompositeVideoClip(VideoClip):A VideoClip made of other videoclips displayed together. This is thebase class for most compositions.++ Parameters- :param size: The size (height x width) of the final clip.+ size+ The size (height x width) of the final clip.- :param clips: A list of videoclips. Each clip of the list will- be displayed below the clips appearing after it in the list.- For each clip:+ clips+ A list of videoclips. Each clip of the list will+ be displayed below the clips appearing after it in the list.+ For each clip:- - The attribute ``pos`` determines where the clip is placed.+ - The attribute ``pos`` determines where the clip is placed.See ``VideoClip.set_pos``- - The mask of the clip determines which parts are visible.+ - The mask of the clip determines which parts are visible.- Finally, if all the clips in the list have their ``duration``- attribute set, then the duration of the composite video clip- is computed automatically+ Finally, if all the clips in the list have their ``duration``+ attribute set, then the duration of the composite video clip+ is computed automatically- :param transparent: if False, the clips are overlaid on a surface+ transparent+ If False, the clips are overlaid on a surfaceof the color `bg_color`. If True, the clips are overlaid ona transparent surface, so that all pixels that are transparentfor all clips will be transparent in the composite clip. Morediff --git a/moviepy/video/tools/subtitles.py b/moviepy/video/tools/subtitles.pynew file mode 100644index 00000000..6eaa6308--- /dev/null+++ b/moviepy/video/tools/subtitles.py@@ -0,0 +1,111 @@+""" Experimental module for subtitles support. """++import re+import numpy as np+from moviepy.video.VideoClip import VideoClip, TextClip++class SubtitlesClip(VideoClip):+ """ A Clip that serves as "subtitle track" in videos.++ One particularity of this class is that the images of the+ subtitle texts are not generated beforehand, but only if+ needed.++ Parameters+ ==========++ subtitles+ Either the name of a file, or a list++ Examples+ =========++ >>> from moviepy.video.tools.subtitles import SubtitlesClip+ >>> from moviepy.video.io.VideoFileClip import VideoFileClip+ >>> generator = lambda txt: TextClip(txt, font='Georgia-Regular',+ fontsize=24, color='white')+ >>> sub = SubtitlesClip("subtitles.srt", generator)+ >>> myvideo = VideoFileClip("myvideo.avi")+ >>> final = CompositeVideoClip([clip, subtitles])+ >>> final.to_videofile("final.mp4", fps=myvideo.fps)+++ """+ def __init__(self, subtitles, gen_textclip=None):++ VideoClip.__init__(self)++ if isinstance( subtitles, str):+ subtitles = file_to_subtitles(subtitles)+ self.subtitles = subtitles+ self.textclips = dict()+ if gen_textclip is None:+ gen_textclip = lambda txt: TextClip(txt, font='Georgia-Bold',+ fontsize=24, color='white',+ stroke_color='black', stroke_width=0.5)+ self.gen_textclip = gen_textclip+ self.start=0+ self.duration = max([tb for ((ta,tb), txt) in self.subtitles])+ self.end=self.duration++ def add_textclip_if_none(t):+ sub =[((ta,tb),txt) for ((ta,tb),txt) in self.textclips.keys()+ if (ta<=t<tb)]+ if sub == []:+ sub = [((ta,tb),txt) for ((ta,tb),txt) in self.subtitles if+ (ta<=t<tb)]+ if sub == []:+ return False+ sub = sub[0]+ if sub not in self.textclips.keys():+ self.textclips[sub] = gen_textclip(sub[1])+ return sub++ def get_frame(t):+ sub = add_textclip_if_none(t)+ return (self.textclips[sub].get_frame(t) if sub+ else np.array([[[0,0,0]]]))++ def mask_get_frame(t):+ sub = add_textclip_if_none(t)+ return (self.textclips[sub].mask.get_frame(t) if sub+ else np.array([[0]]))++ self.get_frame = get_frame+ self.mask = VideoClip(ismask=True, get_frame=mask_get_frame)++++def convert_time(timestring):+ """ Converts a string into seconds """+ nums = map(float, re.findall(r'\d+', timestring))+ return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000++++def file_to_subtitles(filename):+ """ Converts a srt file into subtitles.++ The returned list is of the form ``[((ta,tb),'some text'),...]``+ and can be fed to SubtitlesClip.++ Only works for '.srt' format for the moment.+ """++ with open(filename,'r') as f:+ lines = f.readlines()++ times_texts = []+ current_times , current_text = None, ""++ for line in lines:+ times = re.findall("[0-9]*:[0-9]*:[0-9]*,[0-9]*", line)+ if times != []:+ current_times = map(convert_time, times)+ elif line == '\n':+ times_texts.append((current_times, current_text.strip('\n')))+ current_times, current_text = None, ""+ elif current_times is not None:+ current_text = current_text + line++ return times_texts\ No newline at end of file