Skip to content

Video editing with Python

Version 0.2, many changes in one commit sorry. Now opencv-independant, better sound support, new organisation etc.

Zulkofdc51d29b7ce
diff --git a/examples/README.rst b/examples/README.rst
new file mode 100644
index 00000000..87ecf8cb
--- /dev/null
+++ b/examples/README.rst
@@ -0,0 +1 @@
+This folder contains curated example scripts for editing movies with MoviePy.
diff --git a/examples/compo_from_image.py b/examples/compo_from_image.py
new file mode 100644
index 00000000..578d0006
--- /dev/null
+++ b/examples/compo_from_image.py
@@ -0,0 +1,31 @@
+from moviepy import *
+from moviepy.plugins.segmenting import findObjects
+
+# Load the image specifying the regions.
+im = ImageClip("../../ultracompositing/motif.png")
+
+# Loacate the regions, return a list of ImageClips
+regions = findObjects(im)
+
+
+# Load 7 clips from the US National Parks. Public Domain :D
+clips = [VideoFileClip(n, audio=False).subclip(18,22) for n in
+ [ "../../videos/romo_0004.mov",
+ "../../videos/apis-0001.mov",
+ "../../videos/romo_0001.mov",
+ "../../videos/elma_s0003.mov",
+ "../../videos/elma_s0002.mov",
+ "../../videos/calo-0007.mov",
+ "../../videos/grsm_0005.mov"]]
+
+# fit each clip into its region
+comp_clips = [c.fx(vfx.resize, r.size).\
+ set_mask(r.mask).\
+ set_pos(r.screenpos)
+ for c,r in zip(clips,regions)]
+
+cc = CompositeVideoClip(comp_clips,im.size)
+cc.fx( vfx.resize, 0.6).to_videofile("../../bigcompo.avi")
+
+# Note that this particular composition takes quite a long time of
+# rendering (about 20s on my computer for just 4s of video).
diff --git a/examples/example_with_sound.py b/examples/example_with_sound.py
new file mode 100644
index 00000000..d9590bc8
--- /dev/null
+++ b/examples/example_with_sound.py
@@ -0,0 +1,52 @@
+"""
+Description of the video:
+The screen is split in two parts showing Carry and Audrey at the phone,
+talking at the same time, because it is actually two scenes of a same
+movie put together.
+"""
+
+from moviepy import *
+from moviepy.video.tools.drawing import color_split
+
+
+duration = 6 # duration of the final clip
+
+# LOAD THE MAIN SCENE
+# this small video contains the two scenes that we will put together.
+
+main_clip = VideoFileClip("../../charadePhone.mp4")
+W,H = main_clip.size
+
+
+
+# MAKE THE LEFT CLIP : cut, crop, add a mask
+
+clip_left = main_clip.coreader().subclip(0,duration).\
+ fx( vfx.crop, x1=60, x2=60 + 2*W/3)
+
+mask = color_split((2*W/3,H), p1=(W/3,H), p2=(2*W/3,0),
+ col1=1, col2=0, grad_width=2)
+
+clip_left.mask = ImageClip(mask, ismask=True)
+
+
+
+# MAKE THE RIGHT CLIP : cut, crop, add a mask
+
+clip_right = main_clip.coreader().subclip(21,21+duration).\
+ fx( vfx.crop, x1=70, x2=70+2*W/3)
+
+mask = color_split((2*W/3,H), p1=(2,H), p2=(W/3+2,0),
+ col1=0, col2=1, grad_width=2)
+
+clip_right.mask = ImageClip(mask, ismask=True)
+
+
+
+# ASSEMBLE AND WRITE THE MOVIE TO A FILE
+
+cc = CompositeVideoClip([clip_right.set_pos('right').fx(afx.volumex, 0.4),
+ clip_left.set_pos('left').fx(afx.volumex, 0.4)],
+ size = (W,H))
+
+cc.to_videofile("../../biphone3.avi",fps=24, codec='mpeg4')
diff --git a/examples/headblur.py b/examples/headblur.py
new file mode 100644
index 00000000..e83740bc
--- /dev/null
+++ b/examples/headblur.py
@@ -0,0 +1,52 @@
+import pickle
+
+from moviepy import *
+from moviepy.video.tools.tracking import manual_tracking, to_fxfy
+import moviepy.video.io.ffmpeg as ffmpeg
+
+
+# LOAD THE CLIP (subclip 6'51 - 7'01 of a chaplin movie)
+clip = VideoFileClip("../../videos/chaplin.mp4").subclip((6,51.7),(7,01.3))
+
+# MANUAL TRACKING OF THE HEAD
+
+# the three next lines are for the manual tracking and its saving
+# to a file, it must be commented once the tracking has been done
+# (after the first run of the script for instance).
+# Note that we save the list (ti,xi,yi), not the functions fx and fy
+# (that we will need) because they have dependencies.
+
+#txy, (fx,fy) = manual_tracking(clip, fps=6)
+#with open("../../chaplin_txy.dat",'w+') as f:
+# pickle.dump(txy)
+
+
+
+# IF THE MANUAL TRACKING HAS BEEN PREVIOUSLY DONE,
+# LOAD THE TRACKING DATA AND CONVERT IT TO FUNCTIONS x(t),fy(t)
+
+with open("../../chaplin_txy.dat",'r') as f:
+ fx,fy = to_fxfy( pickle.load(f) )
+
+
+# BLUR CHAPLIN'S HEAD IN THE CLIP
+
+clip_blurred = clip.fx( vfx.headblur, fx, fy, 25)
+
+
+# Generate the text, put in on a grey background
+
+txt = TextClip("Hey you ! \n You're blurry!", color='grey70',
+ size = clip.size, bg_color='grey20',
+ font = "Century-Schoolbook-Italic", fontsize=40)
+
+
+# Concatenate the Chaplin clip with the text clip, add audio
+
+final = concatenate([clip_blurred,txt.set_duration(3)]).\
+ set_audio(clip.audio)
+
+# We write the result to a file. Here we raise the bitrate so that
+# the final video is not too ugly.
+
+final.to_videofile('../../blurredChaplin.avi', bitrate="3000k")
diff --git a/examples/masked_credits.py b/examples/masked_credits.py
new file mode 100644
index 00000000..a8dad5ce
--- /dev/null
+++ b/examples/masked_credits.py
@@ -0,0 +1,27 @@
+from moviepy import *
+from moviepy.video.tools.credits import credits1
+
+# Load the mountains clip, cut it, slow it down, make it look darker
+clip = VideoFileClip('../../videos/badl-0001.mov', audio=False).\
+ subclip(37,46).\
+ fx( vfx.speedx, 0.4).\
+ fx( vfx.colorx, 0.7)
+
+# Save the first frame to later make a mask with GIMP (only once)
+#~ clip.save_frame('../../credits/mountainMask2.png')
+
+
+# Load the mountain mask made with GIMP
+mountainmask = ImageClip('../../credits/mountainMask2.png',ismask=True)
+
+# Generate the credits from a text file
+credits = credits1('../../credits/credits.txt',3*clip.w/4)
+scrolling_credits = credits.set_pos(lambda t:('center',-10*t))
+
+
+# Make the credits scroll. Here, 10 pixels per second
+final = CompositeVideoClip([clip,
+ scrolling_credits,
+ clip.set_mask(mountainmask)])
+
+final.subclip(8,10).to_videofile("../../credits_mountains.avi")
diff --git a/examples/moving_letters.py b/examples/moving_letters.py
new file mode 100644
index 00000000..debbd6b8
--- /dev/null
+++ b/examples/moving_letters.py
@@ -0,0 +1,63 @@
+import numpy as np
+from moviepy import *
+from moviepy.plugins.segmenting import findObjects
+
+# WE CREATE THE TEXT THAT IS GOING TO MOVE, WE CENTER IT.
+
+screensize = (720,460)
+txtClip = TextClip('Cool effect',color='white', font="Amiri-Bold",
+ kerning = 5, fontsize=100)
+cvc = CompositeVideoClip( [txtClip.set_pos('center')],
+ size=screensize, transparent=True)
+
+# WE DEFINE FOUR WAYS OF MOVING THE LETTERS
+
+rotMatrix = lambda a: np.array( [[np.cos(a),np.sin(a)],
+ [-np.sin(a),np.cos(a)]] )
+
+def vortex(screenpos,i,nletters):
+ d = lambda t : 1.0/(0.3+t**8) #damping
+ a = i*np.pi/ nletters # angle of the movement
+ v = rotMatrix(a).dot([-1,0])
+ if i%2 : v[1] = -v[1]
+ return lambda t: screenpos+400*d(t)*rotMatrix(0.5*d(t)*a).dot(v)
+
+def cascade(screenpos,i,nletters):
+ v = np.array([0,-1])
+ d = lambda t : 1 if t<0 else abs(np.sinc(t)/(1+t**4))
+ return lambda t: screenpos+v*400*d(t-0.15*i)
+
+def arrive(screenpos,i,nletters):
+ v = np.array([-1,0])
+ d = lambda t : max(0, 3-3*t)
+ return lambda t: screenpos-400*v*d(t-0.2*i)
+
+def vortexout(screenpos,i,nletters):
+ d = lambda t : max(0,t) #damping
+ a = i*np.pi/ nletters # angle of the movement
+ v = rotMatrix(a).dot([-1,0])
+ if i%2 : v[1] = -v[1]
+ return lambda t: screenpos+400*d(t-0.1*i)*rotMatrix(-0.2*d(t)*a).dot(v)
+
+
+
+# WE USE THE PLUGIN TO LOCATE AND SEPARATE EACH LETTER
+
+letters = findObjects(cvc) # a list of ImageClips
+
+
+# WE ANIMATE THE LETTERS
+
+def moveLetters(letters, funcpos):
+ return [ letter.set_pos(funcpos(letter.screenpos,i,len(letters)))
+ for i,letter in enumerate(letters)]
+
+clips = [ CompositeVideoClip( moveLetters(letters,funcpos),
+ size = screensize).subclip(0,5)
+ for funcpos in [vortex, cascade, arrive, vortexout] ]
+
+# WE CONCATENATE EVERYTHING AND WRITE TO A FILE
+
+concatenate(clips).to_videofile('../../coolTextEffects.avi',
+ fps=25, codec='mpeg4')
+
diff --git a/examples/painting_effect.py b/examples/painting_effect.py
new file mode 100644
index 00000000..da39a3a5
--- /dev/null
+++ b/examples/painting_effect.py
@@ -0,0 +1,38 @@
+""" requires scikit-image installed (for vfx.painting) """
+
+from moviepy import *
+
+# WE TAKE THE SUBCLIPS WHICH ARE 2 SECONDS BEFORE & AFTER THE FREEZE
+
+charade = VideoFileClip("../../videos/charade.mp4")
+tfreeze = cvsecs(19,21) # Time of the freeze, 19'21
+
+clip_before = charade.coreader().subclip(tfreeze -2,tfreeze)
+clip_after = charade.coreader().subclip(tfreeze ,tfreeze +2)
+
+
+# THE FRAME TO FREEZE
+
+im_freeze = charade.to_ImageClip(tfreeze)
+painting = charade.fx( vfx.painting, saturation = 1.6,black = 0.006).\
+ to_ImageClip(tfreeze)
+
+txt = TextClip('Audrey',font='Amiri-regular',fontsize=35)
+
+painting_txt = CompositeVideoClip([painting,txt.set_pos((10,180))]).\
+ add_mask().\
+ set_duration(3).\
+ fx( transfx.crossfadein, 0.5).\
+ fx( transfx.crossfadeout, 0.5)
+
+# FADEIN/FADEOUT EFFECT ON THE PAINTED IMAGE
+
+painting_fading = CompositeVideoClip([im_freeze,painting_txt])
+
+# FINAL CLIP AND RENDERING
+
+final_clip = concatenate([ clip_before,
+ painting_fading.set_duration(3),
+ clip_after])
+
+final_clip.to_videofile('../../audrey.avi',fps=charade.fps, codec = "mpeg4")
diff --git a/examples/soundtrack.py b/examples/soundtrack.py
new file mode 100644
index 00000000..30410d7f
--- /dev/null
+++ b/examples/soundtrack.py
@@ -0,0 +1,23 @@
+""" A simple test script on how to put a soundtrack to a movie """
+from moviepy import *
+
+
+# We load a movie and replace the sound with some music:
+
+movie = VideoFileClip("../../videos/dam.mov").\
+ set_audio( AudioFileClip("../../sounds/startars.ogg") )
+
+
+# If the soundtrack is longer than the movie, then at the end of the clip
+# it will freeze on the last frame and wait for the clip to finish.
+# If you don't want that, uncomment the next line:
+
+#~ movie.audio = movie.audio.set_duration(movie.duration)
+
+#soundtrack.subclip(0,25).preview(fps=22050,buffersize=20000)
+
+movie.fx( vfx.resize, 0.5).\
+ set_audio(soundtrack).\
+ to_videofile("../../test_soundtrack.avi",
+ codec="mpeg4",bitrate="4000k")
+
diff --git a/examples/star_worms.py b/examples/star_worms.py
new file mode 100644
index 00000000..26b733a0
--- /dev/null
+++ b/examples/star_worms.py
@@ -0,0 +1,179 @@
+"""
+Description of the video:
+Mimic of Star Wars' opening title. A text with a (false)
+perspective effect goes towards the end of space, on a
+background made of stars. Slight fading effect on the text.
+
+"""
+
+import numpy as np
+from skimage import transform as tf
+
+from moviepy import *
+from moviepy.video.tools.drawing import color_gradient
+
+
+# RESOLUTION
+
+w = 720
+h = w*9/16 # 16/9 screen
+moviesize = w,h
+
+
+
+# THE RAW TEXT
+txt = "\n".join([
+"A long time ago, in a faraway galaxy,",
+"there lived a prince and a princess",
+"who had never seen the stars, for they",
+"lived deep underground.",
+"",
+"Many years before, the prince's",
+"grandfather had ventured out to the",
+"surface and had been burnt to ashes by",
+"solar winds.",
+"",
+"One day, as the princess was coding",
+"and the prince was shopping online, a",
+"meteor landed just a few megameters",
+"from the couple's flat."
+])
+
+
+# Add blanks
+txt = 10*"\n" +txt + 10*"\n"
+
+
+# CREATE THE TEXT IMAGE
+
+
+clip_txt = TextClip(txt,color='white', align='West',fontsize=25,
+ font='Xolonium-Bold', method='label')
+
+
+# SCROLL THE TEXT IMAGE BY CROPPING A MOVING AREA
+
+txt_speed = 27
+fl = lambda gf,t : gf(t)[int(txt_speed*t):int(txt_speed*t)+h,:]
+moving_txt= clip_txt.fl(fl, applyto=['mask'])
+
+
+# ADD A VANISHING EFFECT ON THE TEXT WITH A GRADIENT MASK
+
+grad = color_gradient(moving_txt.size,p1=(0,2*h/3),
+ p2=(0,h/4),col1=0.0,col2=1.0)
+gradmask = ImageClip(grad,ismask=True)
+fl = lambda pic : np.minimum(pic,gradmask.img)
+moving_txt.mask = moving_txt.mask.fl_image(fl)
+
+
+# WARP THE TEXT INTO A TRAPEZOID (PERSPECTIVE EFFECT)
+
+def trapzWarp(pic,cx,cy,ismask=False):
+ """ Complicated function (will be latex packaged as a fx) """
+ Y,X = pic.shape[:2]
+ src = np.array([[0,0],[X,0],[X,Y],[0,Y]])
+ dst = np.array([[cx*X,cy*Y],[(1-cx)*X,cy*Y],[X,Y],[0,Y]])
+ tform = tf.ProjectiveTransform()
+ tform.estimate(src,dst)
+ im = tf.warp(pic, tform.inverse, output_shape=(Y,X))
+ return im if ismask else (im*255).astype('uint8')
+
+fl_im = lambda pic : trapzWarp(pic,0.2,0.3)
+fl_mask = lambda pic : trapzWarp(pic,0.2,0.3, ismask=True)
+warped_txt= moving_txt.fl_image(fl_im)
+warped_txt.mask = warped_txt.mask.fl_image(fl_mask)
+
+
+# BACKGROUND IMAGE, DARKENED AT 60%
+
+stars = ImageClip('../../starworms/stars.jpg')
+stars_darkened = stars.fl_image(lambda pic: (0.6*pic).astype('int16'))
+
+
+# COMPOSE THE MOVIE
+
+final = CompositeVideoClip([
+ stars, warped_txt.set_pos(('center','bottom'))],
+ size = moviesize)
+
+
+# WRITE TO A FILE
+
+final.set_duration(8).to_videofile("starworms.avi")
+
+# This script is heavy (30s of computations to render 8s of video)
+
+
+
+"""=====================================================================
+
+ CODE FOR THE VIDEO TUTORIAL
+
+ We will now code the video tutorial for this video.
+ When you think about it, it is a code for a video explaining how to
+ make another video using some code (this is so meta !).
+ This code uses the variables of the previous code (it should be placed
+ after that previous code to work).
+
+====================================================================="""
+
+
+
+def annotate(clip,txt,txt_color='white',bg_color=(0,0,255)):
+ """ Writes a text at the bottom of the clip. """
+
+ txtclip = TextClip(txt, fontsize=20, font='Ubuntu-bold',
+ color=txt_color)
+
+ txtclip = txtclip.on_color((clip.w,txtclip.h+6), color=(0,0,255),
+ pos=(6,'center'))
+
+ cvc = CompositeVideoClip([clip , txtclip.set_pos((0,'bottom'))])
+
+ return cvc.set_duration(clip.duration)
+
+
+def resizeCenter(clip):
+ return clip.fx( vfx.resize, height=h).set_pos('center')
+
+
+def composeCenter(clip):
+ return CompositeVideoClip([clip.set_pos('center')],size=moviesize)
+
+
+
+annotated_clips = [ annotate(clip,text) for clip,text in [
+
+(composeCenter(resizeCenter(stars)).subclip(0,3),
+ "This is a public domain picture of stars"),
+
+(CompositeVideoClip([stars],moviesize).subclip(0,3),
+ "We only keep one part."),
+
+(CompositeVideoClip([stars_darkened],moviesize).subclip(0,3),
+ "We darken it a little."),
+
+(composeCenter(resizeCenter(clip_txt)).subclip(0,3),
+ "We generate a text image."),
+
+(composeCenter(moving_txt.set_mask(None)).subclip(6,9),
+ "We scroll the text by cropping a moving region of it."),
+
+(composeCenter(gradmask.to_RGB()).subclip(0,2),
+ "We add this mask to the clip."),
+
+(composeCenter(moving_txt).subclip(6,9),
+ "Here is the result"),
+
+(composeCenter(warped_txt).subclip(6,9),
+ "We now warp this clip in a trapezoid."),
+
+(final.subclip(6,9),
+ "We finally superimpose with the stars.")
+]]
+
+# Concatenate and write to a file
+
+concatenate(annotated_clips).to_videofile('tutorial.avi')
+
diff --git a/examples/the_end.py b/examples/the_end.py
new file mode 100644
index 00000000..5bc784fb
--- /dev/null
+++ b/examples/the_end.py
@@ -0,0 +1,23 @@
+from moviepy import *
+from moviepy.video.tools.drawing import circle
+
+clip = VideoFileClip("../../videos/badl-0006.mov", audio=False).\
+ subclip(26,31).\
+ add_mask()
+
+w,h = clip.size
+
+# The mask is a circle with vanishing radius r(t) = 800-200*t
+clip.mask.get_frame = lambda t: circle(screensize=(clip.w,clip.h),
+ center=(clip.w/2,clip.h/4),
+ radius=max(0,int(800-200*t)),
+ col1=1, col2=0, blur=4)
+
+
+the_end = TextClip("The End", font="Amiri-bold", color="white",
+ fontsize=70).set_duration(clip.duration)
+
+final = CompositeVideoClip([the_end.set_pos('center'),clip],
+ size =clip.size)
+
+final.to_videofile("../../theEnd.avi")
diff --git a/examples/ukulele_concerto.py b/examples/ukulele_concerto.py
new file mode 100644
index 00000000..aa53cd9a
--- /dev/null
+++ b/examples/ukulele_concerto.py
@@ -0,0 +1,42 @@
+from moviepy import *
+
+# UKULELE CLIP, OBTAINED BY CUTTING AND CROPPING
+# RAW FOOTAGE
+
+ukulele = VideoFileClip("../../videos/moi_ukulele.MOV", audio=False).\
+ subclip(60+33, 60+50).\
+ fx( vfx.crop, 486, 180, 1196, 570)
+
+w,h = moviesize = ukulele.size
+
+# THE PIANO FOOTAGE IS DOWNSIZED, HAS A WHITE MARGIN, IS
+# IN THE BOTTOM RIGHT CORNER
+
+piano = (VideoFileClip("../../videos/douceamb.mp4",audio=False).
+ subclip(30,50).
+ fx( vfx.resize, (w/3,h/3)). # one third of the total screen
+ fx( vfx.margin, 6,color=(255,255,255)). #white margin
+ fx( vfx.margin, bottom=20, right=20, opacity=0). # transparent
+ set_pos(('right','bottom')) )
+
+
+
+# A CLIP WITH A TEXT AND A BLACK SEMI-OPAQUE BACKGROUND
+
+txt = TextClip("V. Zulkoninov - Ukulele Sonata", font='Amiri-regular',
+ color='white',fontsize=24)
+
+txt_col = txt.on_color(size=(ukulele.w + txt.w,txt.h-10),
+ color=(0,0,0), pos=(6,'center'), col_opacity=0.6)
+
+
+# THE TEXT CLIP IS ANIMATED.
+# I am *NOT* explaining the formula, understands who can/want.
+txt_mov = txt_col.set_pos( lambda t: (max(w/30,int(w-0.5*w*t)),
+ max(5*h/6,int(100*t))) )
+
+
+
+# FINAL ASSEMBLY
+final = CompositeVideoClip([ukulele,txt_mov,piano])
+final.subclip(0,5).to_videofile("../../ukulele.avi",fps=24,codec='libx264')
diff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.py
new file mode 100644
index 00000000..0eae5bdc
--- /dev/null
+++ b/moviepy/audio/AudioClip.py
@@ -0,0 +1,178 @@
+import time
+import os
+import sys
+import wave
+from copy import copy
+
+import numpy as np
+from io.writers import wave_write
+from io.preview import preview
+from moviepy.decorators import requires_duration
+
+from moviepy.Clip import Clip
+
+
+# optimize range in function of Python's version
+if sys.version_info < (3,):
+ range = xrange
+
+
+class AudioClip(Clip):
+
+ """
+
+ Base class for audio clips. See ``SoundClip`` and ``CompositeSoundClip``
+ for usable classes.
+ An audio clip is a special clip with a ``get_frame`` attribute of
+ the form ` t -> [ f_t ]` for mono sound and `t -> [ f1_t, f2_t ]`
+ for stereo sound. The `f_t` are floats between -1 and 1. These
+ bounds can be trespassed wihtout problems (the program will put the
+ sound back into the bounds at conversion time, without much impact).
+
+ Example :
+
+ >>> # Plays the note A (a sine wave of frequency 404HZ)
+ >>> import numpy as np
+ >>> gf = lambda t : 2*[ np.sin(404 * 2 * np.pi * t) ]
+ >>> clip = AudioClip().set_get_frame(gf)
+ >>> clip.set_duration(5).preview()
+
+
+ :ivar get_frame: A function `t-> frame at time t`. The frame does not
+ mean much for a sound, it is just a float. What 'makes' the sound
+ are the variations of that float in the time.
+
+ :ivar nchannels: Number of channels (one or two for mono or stereo).
+
+ """
+
+ def __init__(self):
+ Clip.__init__(self)
+
+ @requires_duration
+ def to_soundarray(self,tt, nbytes=2):
+ """
+ Transforms the sound into an array that can be played by pygame
+ or written in a wav file. See ``AudioClip.preview``.
+
+ :param fps: frame rate of the sound. 44100 gives top quality.
+
+ :param nbytes: number of bytes to encode the sound: 1 for 8bit
+ sound, 2 for 16bit, 4 for 32bit sound.
+ """
+ snd_array = self.get_frame(tt)
+ snd_array = np.maximum(-0.999, np.minimum(0.999,snd_array))
+ inttype = {1:'int8',2:'int16',4:'int32'}[nbytes]
+ return (2**(8*nbytes-1)*snd_array).astype(inttype)
+
+
+ @requires_duration
+ def preview(self, fps=22050, buffersize=10000, nbytes= 2,
+ audioFlag=None, videoFlag=None):
+ """
+ Plays the sound clip with pygame.
+
+ :param fps: frame rate of the sound. 44100 gives top quality, but
+ may cause problems if your computer is not fast enough and
+ your clip is complicated. If the sound jumps during the
+ preview lower it (11025 is still fine, 5000 is tolerable).
+
+ :param buffersize: The sound is not generated all at once, but
+ rather made by bunches of frames (chunks). ``buffersize``
+ is the size of such a chunk. Try varying it if you meet
+ audio problems (but you shouldn't have to).
+
+ :param nbytes: number of bytes to encode the sound: 1 for 8bit
+ sound, 2 for 16bit, 4 for 32bit sound. 2 bytes is fine.
+
+ :param audioFlag, videoFlag: parameters whose sole purpose is to
+ enable a good synchronization of the start of video and sound
+ when the audio clip is played as the background of a video
+ clip. ``audioFlag`` and ``videoFlag`` are threading.Event
+ objects (from Python's standard threading module).
+ """
+
+ preview(self, fps, buffersize, nbytes, audioFlag, videoFlag)
+
+ @requires_duration
+ def to_audiofile(self, filename, fps=44100, nbytes = 2,
+ buffersize=80000, verbose=True):
+ """ Writes the soundclip to a .wav file. """
+
+ wave_write(self, filename,fps, nbytes, buffersize, verbose)
+
+ @property
+ def nchannels(self):
+ return len(list(self.get_frame(0)))
+
+
+class AudioArrayClip(AudioClip):
+ """
+
+ An audio clip made from a sound array.
+
+ :param fps: Frames per rate
+
+ """
+
+ def __init__(self, array, fps):
+
+ Clip.__init__(self)
+ self.array = array
+ self.fps = fps
+ self.duration = 1.0 * len(array) / fps
+
+
+ def gf(t):
+ """ complicated, but must be able to handle the case where t
+ is a list of the form sin(t) """
+
+ if isinstance(t, np.ndarray):
+ array_inds = int(self.fps*t)
+ in_array = (array_inds>0) & (array_inds < len(self.array))
+ result = np.zeros((len(t),2))
+ result[in_array] = self.array(array_inds[in_array])
+ return results
+ else:
+ i = int(self.fps * t)
+ if i < 0 or i >= len(self.array):
+ return 0*self.array[0]
+ else:
+ return self.array[i]
+
+ self.get_frame = gf
+
+
+
+class CompositeAudioClip(AudioClip):
+
+ """
+
+ An audio clip made by putting together several audio clips.
+
+ :param clips: a list of audio clips, which may start playing at
+ different times or together. If all have their ``duration``
+ attribute set, the duration of the composite clip is computed
+ automatically.
+
+ """
+
+ def __init__(self, clips):
+
+ Clip.__init__(self)
+ self.clips = clips
+
+ ends = [c.end for c in self.clips]
+ if not any([(e is None) for e in ends]):
+ self.duration = max(ends)
+
+ def gf(t):
+ sounds= [c.get_frame(t - c.start)
+ for c in clips if c.is_playing(t)]
+ if isinstance(t,np.ndarray):
+ zero = np.zeros((len(t),2))
+ else:
+ zero = np.zeros(2)
+ return zero + sum(sounds)
+
+ self.get_frame = gf
diff --git a/moviepy/audio/__init__.py b/moviepy/audio/__init__.py
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/moviepy/audio/__init__.py
@@ -0,0 +1 @@
+
diff --git a/moviepy/audio/fx/__init__.py b/moviepy/audio/fx/__init__.py
new file mode 100644
index 00000000..a58dd727
--- /dev/null
+++ b/moviepy/audio/fx/__init__.py
@@ -0,0 +1,14 @@
+"""
+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/audio_fadein.py b/moviepy/audio/fx/audio_fadein.py
new file mode 100644
index 00000000..0505de65
--- /dev/null
+++ b/moviepy/audio/fx/audio_fadein.py
@@ -0,0 +1,8 @@
+from moviepy.decorators import audio_video_fx
+
+@audio_video_fx
+def audio_fadein(clip, duration):
+ """ Return an audio (or video) clip that is first mute, then the
+ sound arrives progressively over ``duration`` seconds. """
+ fading = lambda gf, t: min(1.0 * t / duration, 1) * gf(t)
+ return clip.fl(fading, keep_duration = True)
diff --git a/moviepy/audio/fx/audio_fadeout.py b/moviepy/audio/fx/audio_fadeout.py
new file mode 100644
index 00000000..1d8a44b6
--- /dev/null
+++ b/moviepy/audio/fx/audio_fadeout.py
@@ -0,0 +1,10 @@
+from moviepy.decorators import audio_video_fx, requires_duration
+
+@audio_video_fx
+@requires_duration
+def audio_fadeout(self, duration):
+ """ Return a sound clip where the sound fades out progressively
+ over ``duration`` seconds at the end of the clip. """
+ fading = lambda gf, t: max(
+ 1.0 * (self.duration - t) / duration, 0) * gf(t)
+ return self.fl(fading, keep_duration = True)
diff --git a/moviepy/audio/fx/volumex.py b/moviepy/audio/fx/volumex.py
new file mode 100644
index 00000000..8149135f
--- /dev/null
+++ b/moviepy/audio/fx/volumex.py
@@ -0,0 +1,6 @@
+from moviepy.decorators import audio_video_fx
+
+@audio_video_fx
+def volumex(clip, factor):
+ """ Returns a (video or audio) clip with increased sound volume """
+ return clip.fl(lambda gf, t: factor * gf(t), keep_duration = True)
diff --git a/moviepy/audio/io/AudioFileClip.py b/moviepy/audio/io/AudioFileClip.py
new file mode 100644
index 00000000..9cb35183
--- /dev/null
+++ b/moviepy/audio/io/AudioFileClip.py
@@ -0,0 +1,121 @@
+import wave
+import numpy as np
+
+from moviepy.Clip import Clip
+from moviepy.audio.AudioClip import AudioClip
+from moviepy.audio.io.readers import FFMPEG_AudioReader
+
+class AudioFileClip(AudioClip):
+
+ """
+
+ An audio clip read from a sound file, or an array.
+ The whole file is not loaded in memory. Instead, only a portion is
+ read and stored in memory. this portion includes frames before
+ and after the last frames read, so that it is fast to read the sound
+ backward and forward.
+
+
+ :param snd: Either a soundfile or an array representing a sound. If
+ the soundfile is not a .wav, it will be converted to .wav first,
+ using the ``fps`` and ``bitrate`` arguments.
+
+ :param buffersize: Size to load in memory (in number of frames)
+ :param temp_wav: name for the temporary wav file in case conversion
+ is required. If not provided, the default will be filename.wav
+ with some prefix. If the temp_wav already exists it will not
+ be rewritten.
+
+ :ivar nbytes: Number of bits per frame of the original audio file
+ (the more the better).
+ :ivar fps, buffersize: see above.
+
+ >>> snd = SoundClip("song.wav")
+ >>> snd = SoundClip("song.mp3", fps = 44100, bitrate=3000)
+ >>> snd = SoundClip(mySoundArray,fps=44100) # from a numeric array
+
+ """
+
+ def __init__(self, filename, buffersize=200000, nbytes=2, fps=44100):
+
+
+ Clip.__init__(self)
+
+ self.filename = filename
+ self.reader = FFMPEG_AudioReader(filename,fps=fps,nbytes=nbytes)
+ self.fps = fps
+ self.duration = self.reader.duration
+ self.nframes = self.reader.nframes
+ self.buffersize= buffersize
+ self.buffer=None
+ self._fstart_buffer = 1
+ self._buffer_around(1)
+ self.nchannels = self.reader.nchannels
+
+ def gf(t):
+ bufsize = self.buffersize
+ if isinstance(t,np.ndarray):
+ # lazy implementation, but should not cause problems in
+ # 99.99 % of the cases
+ result = np.zeros((len(t),2))
+ in_time = (t>=0) & (t < self.duration)
+ inds = (self.fps*t+1).astype(int)[in_time]
+ f_tmin, f_tmax = inds.min(), inds.max()
+
+ if not (0 <= (f_tmin - self._fstart_buffer) < len(self.buffer)):
+ self._buffer_around(f_tmin)
+ elif not (0 <= (f_tmax - self._fstart_buffer) < len(self.buffer)):
+ self._buffer_around(f_tmax)
+
+ try:
+ result[in_time] = self.buffer[inds - self._fstart_buffer]
+ return result
+ except:
+ print ("Error: wrong indices in video buffer. Maybe"+
+ " buffer too small.")
+ raise
+ else:
+ ind = int(self.fps*t)+1
+ if ind<1 or ind> self.nframes: # out of time: return 0
+ return np.zeros(self.nchannels)
+
+ if not (0 <= (ind - self._fstart_buffer) <len(self.buffer)):
+ # out of the buffer: recenter the buffer
+ self._buffer_around(ind)
+
+ # read the frame in the buffer
+ return self.buffer[ind - self._fstart_buffer]
+
+ self.get_frame = gf
+
+ def _buffer_around(self,framenumber):
+ """ fill the buffer with frames, centered on ``framenumber``
+ if possible
+ """
+ # start frame for the buffer
+ fbuffer = framenumber - self.buffersize/2
+ fbuffer = max(1, fbuffer)
+
+
+ if (self.buffer!=None):
+ current_f_end =self._fstart_buffer + self.buffersize-1
+ if (fbuffer < current_f_end < fbuffer+ self.buffersize):
+ # We already have one bit of what must be read
+ conserved = current_f_end - fbuffer+1
+ chunksize = self.buffersize-conserved
+ array = self.reader.read_chunk(chunksize)
+ self.buffer = np.vstack([self.buffer[-conserved:], array])
+ else:
+ self.reader.seek(fbuffer)
+ self.buffer = self.reader.read_chunk(self.buffersize)
+ else:
+ self.reader.seek(fbuffer)
+ self.buffer = self.reader.read_chunk(self.buffersize)
+
+ self._fstart_buffer = fbuffer
+
+ def coreader(self):
+ """ Returns a copy of the AudioFileClip, i.e. a new entrance point
+ to the audio file. Use copy when you have different clips
+ watching the audio file at different times. """
+ return AudioFileClip(self.filename,self.buffersize)
diff --git a/moviepy/audio/io/__init__.py b/moviepy/audio/io/__init__.py
new file mode 100644
index 00000000..21b9da62
--- /dev/null
+++ b/moviepy/audio/io/__init__.py
@@ -0,0 +1,3 @@
+"""
+Class and methods to read, write, preview audiofiles.
+"""
diff --git a/moviepy/audio/io/preview.py b/moviepy/audio/io/preview.py
new file mode 100644
index 00000000..696d91b8
--- /dev/null
+++ b/moviepy/audio/io/preview.py
@@ -0,0 +1,57 @@
+import time
+import numpy as np
+import threading
+
+import numpy as np
+
+from moviepy.decorators import requires_duration
+import pygame as pg
+
+@requires_duration
+def preview(clip, fps=22050, buffersize=50000, nbytes= 2,
+ audioFlag=None, videoFlag=None):
+ """
+ Plays the sound clip with pygame.
+
+ :param fps: frame rate of the sound. 44100 gives top quality, but
+ may cause problems if your computer is not fast enough and
+ your clip is complicated. If the sound jumps during the
+ preview lower it (11025 is still fine, 5000 is tolerable).
+
+ :param buffersize: The sound is not generated all at once, but
+ rather made by bunches of frames (chunks). ``buffersize``
+ is the size of such a chunk. Try varying it if you meet
+ audio problems (but you shouldn't have to).
+
+ :param nbytes: number of bytes to encode the sound: 1 for 8bit
+ sound, 2 for 16bit, 4 for 32bit sound. 2 bytes is fine.
+
+ :param audioFlag, videoFlag: parameters whose sole purpose is to
+ enable a good synchronization of the start of video and sound
+ when the audio clip is played as the background of a video
+ clip. ``audioFlag`` and ``videoFlag`` are threading.Event
+ objects (from Python's standard threading module).
+ """
+
+ pg.mixer.quit()
+
+ pg.mixer.init(fps, -8 * nbytes, clip.nchannels, 1024)
+ totalsize = int(fps*clip.duration)
+ pospos = np.array(list(range(0, totalsize, buffersize))+[totalsize])
+ tt = (1.0/fps)*np.arange(pospos[0],pospos[1])
+ sndarray = clip.to_soundarray(tt,nbytes)
+ chunk = pg.sndarray.make_sound(sndarray)
+ Delta = tt[1]-tt[0]
+ if audioFlag and videoFlag:
+ audioFlag.set()
+ videoFlag.wait()
+
+ channel = chunk.play()
+ t0 = time.time()
+ for i in range(1,len(pospos)-1):
+ tt = (1.0/fps)*np.arange(pospos[i],pospos[i+1])
+ sndarray = clip.to_soundarray(tt,nbytes)
+ chunk = pg.sndarray.make_sound(sndarray)
+ channel.queue(chunk)
+ t1 = time.time()
+ time.sleep(max(0,tt[i]-Delta- (t1-t0)))
diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.py
new file mode 100644
index 00000000..c6a2f154
--- /dev/null
+++ b/moviepy/audio/io/readers.py
@@ -0,0 +1,161 @@
+import subprocess as sp
+import re
+import time
+import os
+
+import numpy as np
+
+#from moviepy.clip import Clip
+from moviepy.tools import cvsecs
+from moviepy.video.io.preview import imdisplay
+from moviepy.conf import FFMPEG_BINARY
+from moviepy.tools import cvsecs
+
+
+
+
+class FFMPEG_AudioReader:
+ """ streams any file (audio or video) and outputs a 16bit 44100HZ
+ wav that can be read by the moviepy AudioFileClip. """
+
+ def __init__(self, filename, print_infos=False, fps=44100, nbytes=2):
+ self.filename = filename
+ self.nbytes = nbytes
+ self.fps = fps
+ self.f = 's%dle'%(8*nbytes)
+ self.acodec = 'pcm_s%dle'%(8*nbytes)
+ self.nchannels = 2
+ self.load_infos()
+ self.initialize()
+
+
+
+
+ def initialize(self):
+ """ Opens the file, creates the pipe. """
+
+ cmd = [ FFMPEG_BINARY, '-i', self.filename, '-vn',
+ '-f', self.f,
+ '-acodec', self.acodec,
+ '-ar', "%d"%self.fps,
+ '-ac', '%d'%self.nchannels, '-']
+ self.proc = sp.Popen( cmd, stdin=sp.PIPE,
+ stdout=sp.PIPE,
+ stderr=sp.PIPE)
+ self.pos = 1
+
+ def load_infos(self, print_infos=False):
+ """ reads the FFMPEG info on the file and sets self.size
+ and self.fps """
+ # open the file in a pipe, provoke an error, read output
+ proc = sp.Popen([FFMPEG_BINARY,"-i",self.filename, "-"],
+ stdin=sp.PIPE,
+ stdout=sp.PIPE,
+ stderr=sp.PIPE)
+ proc.stdout.readline()
+ proc.terminate()
+ infos = proc.stderr.read()
+ if print_infos:
+ # print the whole info text returned by FFMPEG
+ print infos
+
+ lines = infos.splitlines()
+
+ if "No such file or directory" in lines[-1]:
+ raise IOError("%s not found ! Wrong path ?"%self.filename)
+
+ # get duration (in seconds)
+ line = [l for l in lines if 'Duration: ' in l][0]
+ match = re.search(" [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9]",line)
+ hms = map(float,line[match.start()+1:match.end()].split(':'))
+ self.duration = cvsecs(*hms)
+ self.nframes = int(self.duration*self.fps)
+
+
+ def reinitialize(self,starttime=0):
+ """ Restarts the reading, starts at an arbitrary
+ location (!! SLOW !!) """
+ self.close()
+ if starttime==0:
+ self.initialize()
+ else:
+ offset = min(1,starttime)
+ print "OFFFFSET, start", offset, starttime
+ cmd = [ FFMPEG_BINARY,
+ "-ss", "%.05f"%(starttime-offset),
+ '-i', self.filename, '-vn',
+ "-ss", "%.05f"%offset,
+ '-f', self.f,
+ '-acodec', self.acodec,
+ '-ar', "%d"%self.fps,
+ '-ac', '%d'%self.nchannels, '-']
+ self.proc = sp.Popen(cmd, stdin=sp.PIPE,
+ stdout=sp.PIPE,
+ stderr=sp.PIPE)
+ self.pos = int(self.fps*starttime)+1
+
+ def skip_chunk(self,chunksize):
+ s = self.proc.stdout.read(self.nchannels*chunksize*self.nbytes)
+ self.proc.stdout.flush()
+ self.pos = self.pos+chunksize
+
+ def read_chunk(self,chunksize):
+ s = self.proc.stdout.read(self.nchannels*chunksize*self.nbytes)
+ dt = {1: 'int8',2:'int16',4:'int32'}[self.nbytes]
+ result = np.fromstring(s, dtype=dt)
+ result = (1.0*result / 2**(8*self.nbytes-1)).\
+ reshape((len(result)/self.nchannels,
+ self.nchannels))
+ self.proc.stdout.flush()
+ self.pos = self.pos+chunksize
+ return result
+
+ def seek(self,pos):
+ """ Reads a frame at time t. Note for coders:
+ getting an arbitrary frame in the video with ffmpeg can be
+ painfully slow if some decoding has to be done. This
+ function tries to avoid fectching arbitrary frames whenever
+ possible, by moving between adjacent frames.
+ """
+ if (pos < self.pos) or (pos> (self.pos+1000000)):
+ t = 1.0*pos/self.fps
+ self.reinitialize(t)
+ elif pos > self.pos:
+ self.skip_chunk(pos-self.pos)
+ self.pos = pos
+
+ def close(self):
+ self.proc.terminate()
+ for std in self.proc.stdin,self.proc.stdout,self.proc.stderr:
+ std.close()
+ del self.proc
+
+
+
+
+
+class WaveReader:
+
+ def __init__(self, filename):
+ if not filename.endswith('.wav'):
+ name, ext = os.path.splitext(os.path.basename(filename))
+ if temp_wav is None:
+ filename = Clip._TEMP_FILES_PREFIX + filename+'.wav'
+ if not os.exists(filename):
+ ffmpeg.extract_sound(filename, temp, fps, bitrate)
+
+ self.filename = filename
+
+ wavf = wave.open(filename)
+ self.nchannels = wavf.getnchannels()
+ self.fps = wavf.getframerate()
+ self.nframes = wavf.getnframes()
+ self.nbytes = wavf.getsampwidth()
+ self._wavfile = wavf
+
+ self.duration = (1.0*self.nframes/self.fps)
+ self.end = self.duration
+ self.np_dtype = {1:'int8',2:'int16',4:'int32'}[self.nbytes]
+
+ self.buffersize= buffersize
+ self._buffer_around(0)
diff --git a/moviepy/audio/io/writers.py b/moviepy/audio/io/writers.py
new file mode 100644
index 00000000..8772b1ab
--- /dev/null
+++ b/moviepy/audio/io/writers.py
@@ -0,0 +1,38 @@
+import sys
+import wave
+import numpy as np
+
+
+def wave_write(clip, filename,fps, nbytes, buffersize, verbose):
+ """ Writes an audioclip down to a wav file. Deprecated if the
+ ffmpeg writer works as expected. Otherwise, a good safety wheel
+ """
+ if verbose:
+ def verbose_print(s):
+ sys.stdout.write(s)
+ sys.stdout.flush()
+ else:
+ verbose_print = lambda *a : None
+
+ verbose_print("Rendering audio %s\n"%filename)
+
+ totalsize = int(fps*clip.duration)
+ # initialize the wave file with Python's wave module
+ wavf = wave.open(filename, 'wb')
+ wavf.setnchannels(clip.nchannels)
+ wavf.setsampwidth(nbytes)
+ wavf.setframerate(fps)
+ wavf.setnframes(totalsize)
+
+ # Simply append chunks with Python's open
+ nchunks = totalsize / buffersize + 1
+ pospos = np.array(list(range(0, totalsize, buffersize))+[totalsize])
+ ifeedback = max(1,nchunks/10)
+ for i in range(nchunks):
+ if ( (i% ifeedback) == 0): verbose_print("=")
+ tt = (1.0/fps)*np.arange(pospos[i],pospos[i+1])
+ sndarray = clip.to_soundarray(tt,nbytes)
+ wavf.writeframes(sndarray.tostring())
+ wavf.close()
+
+ verbose_print("audio done!")
diff --git a/moviepy/conf.py b/moviepy/conf.py
new file mode 100644
index 00000000..a9faf319
--- /dev/null
+++ b/moviepy/conf.py
@@ -0,0 +1,48 @@
+"""
+Name (and location if needed) of the FFMPEG binary. It will be
+"ffmpeg" on linux, certainly "ffmpeg.exe" on windows, else any path.
+If not provided (None), the system will look for the right version
+automatically each time you launch moviepy.
+If you run this script file it will check that the
+path to the ffmpeg binary (FFMPEG_BINARY)
+"""
+
+FFMPEG_BINARY = None
+
+
+
+# --------------------------------------------------------------------
+
+import subprocess as sp
+
+def tryffmpeg(FFMPEG_BINARY):
+ try:
+ proc = sp.Popen([FFMPEG_BINARY],
+ stdout=sp.PIPE,
+ stderr=sp.PIPE)
+ proc.wait()
+ except:
+ return False
+ else:
+ return True
+
+
+if FFMPEG_BINARY is None:
+
+ if tryffmpeg('ffmpeg'):
+ FFMPEG_BINARY = 'ffmpeg'
+ elif tryffmpeg('ffmpeg.exe'):
+ FFMPEG_BINARY = 'ffmpeg.exe'
+ else:
+ raise IOError("FFMPEG binary not found. Try installing MoviePy"\
+ " manually and specify the path to the binary in"\
+ " the file conf.py")
+
+
+if __name__ == "__main__":
+ if tryffmpeg(FFMPEG_BINARY):
+ print "MoviePy : ffmpeg successfully found."
+ else:
+ print "MoviePy : can't find ffmpeg."
+
+
diff --git a/moviepy/decorators.py b/moviepy/decorators.py
new file mode 100644
index 00000000..d1d46c8e
--- /dev/null
+++ b/moviepy/decorators.py
@@ -0,0 +1,62 @@
+"""
+all decorators used in moviepy go there
+"""
+
+import decorator
+from moviepy.tools import cvsecs
+
+def apply_to_mask(f, clip, *a, **k):
+ """ This decorator will apply the same function f to the mask of
+ the clip created with f """
+ newclip = f(clip, *a, **k)
+ if hasattr(newclip, 'mask') and (newclip.mask != None):
+ newclip.mask = f(newclip.mask, *a, **k)
+ return newclip
+
+
+def apply_to_audio(f, clip, *a, **k):
+ """ This decorator will apply the function f to the audio of
+ the clip created with f """
+ newclip = f(clip, *a, **k)
+ if hasattr(newclip, 'audio') and (newclip.audio != None):
+ newclip.audio = f(newclip.audio, *a, **k)
+ return newclip
+
+
+def requires_duration(f, clip, *a, **k):
+ """ will raise an error if the clip has no duration."""
+ if clip.duration is None:
+ raise ValueError("Attribute 'duration' not set")
+ else:
+ return f(clip, *a, **k)
+
+def audio_video_fx(f, clip, *a, **k):
+ """
+ This decorator tells that the function f (audioclip -> audioclip)
+ can be also used on a video clip, at which case it returns a
+ videoclip with modified audio.
+ """
+
+ if hasattr(clip, "audio"):
+ newclip = clip.copy()
+ if clip.audio != None:
+ newclip.audio = f(clip.audio, *a, **k)
+ return newclip
+ else:
+ return f(clip, *a, **k)
+
+def time_can_be_tuple(f, clip, *a, **k):
+ """
+ This decorator tells that the function f (audioclip -> audioclip)
+ can be also used on a video clip, at which case it returns a
+ videoclip with modified audio.
+ """
+ fun = lambda e: e if (not isinstance(e,tuple)) else cvsecs(*e)
+ a = map(fun,a)
+ k = dict( [(m, fun(n)) for m,n in k.items()])
+ return f(clip, *a, **k)
diff --git a/moviepy/tools.py b/moviepy/tools.py
new file mode 100644
index 00000000..2cf5fd2b
--- /dev/null
+++ b/moviepy/tools.py
@@ -0,0 +1,17 @@
+"""
+Misc. useful functions
+"""
+
+def cvsecs(*args):
+ """ converts a time to second. Either cvsecs(min,secs) or
+ cvsecs(hours,mins,secs).
+ >>> cvsecs(5.5) # -> 5.5 seconds
+ >>> cvsecs(10, 4.5) # -> 604.5 seconds
+ >>> cvsecs(1, 0, 5) # -> 3605 seconds
+ """
+ if len(args) == 1:
+ return args[0]
+ elif len(args) == 2:
+ return 60*args[0]+args[1]
+ elif len(args) ==3:
+ return 3600*args[0]+60*args[1]+args[2]
diff --git a/moviepy/video/ImageClip.py b/moviepy/video/ImageClip.py
new file mode 100644
index 00000000..5e22b1a9
--- /dev/null
+++ b/moviepy/video/ImageClip.py
@@ -0,0 +1,257 @@
+"""
+Classes for advantageous handling of static clips.
+ImageClip, ColorClip, TextClip
+"""
+
+import subprocess
+import os
+import numpy as np
+
+import VideoClip as VC
+import io.readers as readers
+
+
+
+class ImageClip(VC.VideoClip):
+
+ """
+
+ A video clip originating from a picture. This clip will simply
+ display the given picture at all times. For instance:
+
+ >>> clip = ImageClip("myHouse.jpeg")
+ >>> clip = ImageClip( someArray ) # a Numpy array represent
+
+ :param img: Any picture file (png, tiff, jpeg, etc.) or any array
+ representing an RGB image (for instance a frame from a VideoClip
+ or a picture read with scipy of skimage's imread method).
+
+ :param ismask: `True` if the clip is a mask.
+ :param transparent: `True` (default) if you want the alpha layer
+ of the picture (if it exists) to be used as a mask.
+
+ :ivar img: array representing the image of the clip.
+
+ """
+
+ def __init__(self, img, ismask=False, transparent=True, fromalpha=False):
+
+ VC.VideoClip.__init__(self, ismask=ismask)
+
+ if isinstance(img, str):
+ img = readers.read_image(img,with_mask=transparent)
+
+ if len(img.shape) == 3: # img is (now) a RGB(a) numpy array
+
+ if img.shape[2] == 4:
+ if fromalpha:
+ img = 1.0 * img[:, :, 3] / 255
+ elif ismask:
+ img = 1.0 * img[:, :, 0] / 255
+ elif transparent:
+ self.mask = ImageClip(
+ 1.0 * img[:, :, 3] / 255, ismask=True)
+ img = img[:, :, :3]
+ elif ismask:
+ img = 1.0 * img[:, :, 0] / 255
+
+ # if the image was just a 2D mask, it should arrive here unchanged
+ self.get_frame = lambda t: img
+ self.size = img.shape[:2][::-1]
+ self.img = img
+
+ def fl(self, fl, applyto=[], keep_duration=True):
+ """
+ Equivalent to VideoClip.fl . The result is no more an
+ ImageClip, it has the class VideoClip (as it may be animated)
+ """
+ # When we use fl on an image clip it may become animated.
+ #Therefore the result is not an ImageClip, just a VideoClip.
+ newclip = VC.VideoClip.fl(self,fl, applyto=applyto,
+ keep_duration=keep_duration)
+ newclip.__class__ = VC.VideoClip
+ return newclip
+
+ def fl_image(self, image_func, applyto= []):
+ """
+ Similar to VideoClip.fl_image, but for ImageClip the
+ tranformed clip is computed once and for all at the beginning,
+ and not for each 'frame'.
+ """
+
+ newclip = self.copy()
+ arr = image_func(self.get_frame(0))
+ newclip.size = arr.shape[:2][::-1]
+ newclip.get_frame = lambda t: arr
+ newclip.img = arr
+
+ for attr in applyto:
+ if hasattr(newclip, attr):
+ a = getattr(newclip, attr)
+ if a != None:
+ setattr(newclip, attr, a.fl_image(image_func))
+
+ return newclip
+
+ def fl_time(self, applyto =['mask', 'audio']):
+ """
+ This method does nothing for ImageClips (but it may affect their
+ masks of their audios). The result is still an ImageClip
+ """
+ newclip = copy(self, keep_class=True)
+
+ for attr in applyto:
+ if hasattr(newclip, attr):
+ a = getattr(newclip, attr)
+ if a != None:
+ setattr(newclip, attr, a.fl_image(image_func))
+
+ return newclip
+
+
+
+
+
+
+class ColorClip(ImageClip):
+ """
+ An ImageClip showing just one color.
+ :param size: Size (width, height) in pixels of the clip
+ :param color: If argument ``ismask`` is False, ``color`` indicates
+ the color in RGB of the clip (default is black). If `ismask``
+ is True, ``color`` must be a float between 0 and 1 (default is 1)
+ :param ismask: Is the clip a mask clip ?
+ """
+ def __init__(self,size, col=(0, 0, 0), ismask=False):
+ w, h = size
+ shape = (h, w) if np.isscalar(col) else (h, w, len(col))
+ ImageClip.__init__(self, np.tile(col, w * h).reshape(shape),
+ ismask=ismask)
+
+
+
+class TextClip(ImageClip):
+
+ """
+
+ An image clip originating from a script-generated text image.
+ Makes a text PNG using ImageMagick.
+
+ :param txt: either a string, or a filename. If txt is in a file and
+ whose name is ``mytext.txt`` for instance, then txt must be
+ equal to ``@mytext.txt`` .
+
+ :param size: Size of the picture in pixels. Can be auto-set if
+ method='label', but mandatory if method='caption'.
+ the height can be None, it will then be auto-determined.
+
+ :param bg_color: Color of the background. See ``TextClip.list('color')``
+ for a list of acceptable names.
+
+ :param color: Color of the background. See ``TextClip.list('color')``
+ for a list of acceptable names.
+
+ :param font: Name of the font to use. See ``TextClip.list('font')`` for
+ the list of fonts you can use on your computer.
+
+ :param stroke_color: Color of the stroke (=contour line) of the text.
+ if ``None``, there will be no stroke.
+
+ :param stroke_width: Width of the strocke, in pixels. Can be a float,
+ like 1.5.
+
+ :param method: 'label' (the picture will be autosized so as to fit
+ exactly the size) or 'caption' (the text will be drawn in a picture
+ with fixed size provided with the ``size`` argument). If `caption`,
+ the text will be wrapped automagically (sometimes it is buggy, not
+ my fault, complain to the ImageMagick crew) and can be aligned or
+ centered (see parameter ``align``).
+
+ :param kerning: Changes the default spacing between letters. For
+ instance ``kerning=-1`` will make the letters 1 pixel nearer from
+ each other compared to the default spacing.
+
+ :param align: center | East | West | South | North . Will work if
+ ``method`` is set to ``caption``
+
+ :param transparent: ``True`` (default) if you want to take into account
+ the transparency in the image.
+
+ """
+
+ def __init__(self, txt, size=None, color='black', bg_color='transparent',
+ fontsize=None, font='Times-New-Roman-Regular',
+ stroke_color=None, stroke_width=1, method='label',
+ kerning=None, align='center', interline=None,
+ tempfile='temp.png',
+ temptxt='temp.txt', transparent=True, remove_temp=True,
+ print_cmd=False):
+
+ if not txt.startswith('@'):
+ temptxt = 'temp.txt'
+ with open(temptxt, 'w+') as f:
+ f.write(txt)
+ txt = '@temp.txt'
+ else:
+ txt = "'%s'"%txt
+
+ if size != None:
+ size = ('' if size[0] is None else str(size[0]),
+ '' if size[1] is None else str(size[1]))
+
+ cmd = ( ["convert",
+ "-background", bg_color,
+ "-fill", color,
+ "-font", font])
+
+ if fontsize !=None:
+ cmd += ["-pointsize", "%d"%fontsize]
+ if kerning != None:
+ cmd += ["-kerning", "%0.1f"%kerning]
+ if stroke_color != None:
+ cmd += ["-stroke", stroke_color, "-strokewidth",
+ "%.01f"%stroke_width]
+ if size != None:
+ cmd += ["-size", "%sx%s"%(size[0], size[1])]
+ if align != None:
+ cmd += ["-gravity",align]
+ if interline != None:
+ cmd += ["-interline-spacing", "%d"%interline]
+
+ cmd += ["%s:%s" %(method, txt),
+ "-type", "truecolormatte", tempfile]
+
+ if print_cmd:
+ print " ".join(cmd)
+
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+ proc.wait()
+ if proc.returncode:
+ print ("Error: problem in the generation of the text file"+
+ "by ImageMagick. Certainly wrong arguments in TextClip")
+ ImageClip.__init__(self, tempfile, transparent=transparent)
+ self.txt = txt
+ self.color = color
+ self.stroke_color = stroke_color
+
+ if remove_temp:
+ os.remove(tempfile)
+ try:
+ os.remove(temptxt)
+ except:
+ pass
+
+ @staticmethod
+ def list(arg):
+ """ Returns the list of all valid entries for the argument given
+ (can be ``font``, ``color``, etc...)
+ argument of ``TextClip`` """
+ process = subprocess.Popen(['convert', '-list', arg],
+ stdout=subprocess.PIPE)
+ result = process.communicate()[0]
+ lines = result.splitlines()
+
+ if arg == 'font':
+ return [l[8:] for l in lines if l.startswith(" Font:")]
+ elif arg == 'color':
+ return [l.split(" ")[1] for l in lines[2:]]
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
new file mode 100644
index 00000000..ef1938ba
--- /dev/null
+++ b/moviepy/video/VideoClip.py
@@ -0,0 +1,498 @@
+"""
+This module implements VideoClip (base class for video clips) and its
+main subclasses:
+- Animated clips: VideofileClip, DirectoryClip
+- Static image clips: ImageClip, ColorClip, TextClip,
+"""
+
+import time
+import os
+import sys
+import subprocess
+import multiprocessing
+import threading
+from copy import copy
+
+
+import numpy as np
+
+from moviepy.decorators import apply_to_mask, requires_duration
+
+import moviepy.audio.io as aio
+import io.ffmpeg as ffmpeg
+import io as vio
+import ImageClip as ImClip
+from moviepy.Clip import Clip
+from tools.drawing import blit
+
+
+
+class VideoClip(Clip):
+
+ """
+
+ Base class for video clips. See ``VideofileClip``, ``ImageClip`` etc. for
+ more user-friendly classes.
+
+ :param ismask: `True` if the clip is going to be used as a mask.
+
+ :ivar size: the size of the clip, (width,heigth), in pixels.
+ :ivar w: te width of the clip, in pixels.
+ :ivar h: te height of the clip, in pixels.
+
+
+ :ivar get_frame: A function ( t-> frame at time t )
+
+ :ivar mask: VideoClip mask attached to this clip. If mask is ``None``,
+ The video clip is fully opaque.
+
+ :ivar audio: A :class:AudioClip attached to the video clip.
+
+ :ivar pos: a function ``t->(x,y)`` where ``x,y`` is the position
+ in pixels of the clip when it is composed with other clips.
+ See ``VideoClip.set_pos``
+
+ :ivar relative_pos: see variable ``pos``.
+
+ :ivar ismask: Boolean set to `True` if the clip is a mask.
+
+
+ """
+
+ def __init__(self, ismask=False):
+ Clip.__init__(self)
+ self.mask = None
+ self.audio = None
+ self.pos = lambda t: (0, 0)
+ self.relative_pos = False
+ self.ismask = ismask
+
+ @property
+ def w(self):
+ return self.size[0]
+
+ @property
+ def h(self):
+ return self.size[1]
+
+ def save_frame(self, filename, t=0, savemask=False):
+ """
+ Saves the frame of clip corresponding to time ``t`` in
+ 'filename'. If ``savemask`` is ``True`` the mask is saved in the
+ alpha layer of the picture.
+ """
+ im = self.get_frame(t)
+ if savemask:
+ mask = 255 * self.mask.get_frame(t)
+ im = np.dstack([im, mask]).astype('uint8')
+ write_image(filename, im)
+
+ @requires_duration
+ def to_directory(self, foldername, fps, transparent=True,
+ overwrite=True, startFrame=0):
+ """
+ Writes the frames of the clip into a folder as png format,
+ and returns the :class:DirectoryClip associated with this
+ folder
+
+ :param foldername: name of the folder (what did you expect ?)
+
+ :param fps: Number of frames per second of movie.
+
+ :param transparent: If `True`, the png images generated will
+ possess an alpha layer representing the mask of the clip.
+
+ :param overwrite: If `True`, will overwrite the content of
+ `folder` if already existing.
+
+ :param startFrame: Useless for the moment, but may come in handy
+ once parallelization is implemented.
+
+ """
+ print "writing frames in [%s]" % foldername,
+
+ try:
+ os.mkdir(foldername)
+ except:
+ if not overwrite:
+ print "Error: Maybe set overwrite =true "
+
+ tt = np.arange(0, self.duration, 1.0 / fps)
+ tt_feedback = tt[::len(tt) / 10]
+
+ for i, t in list(enumerate(tt))[startFrame:]:
+
+ picname = "%s/%s%06d.png" % (foldername, foldername, i)
+ pic = self.get_frame(t)
+ if transparent and (self.mask is not None):
+ fmask = self.mask.get_frame(t)
+ pic = np.dstack([pic, 255 * fmask]).astype('uint8')
+ imsave(picname, pic)
+ if t in tt_feedback:
+ print "%d" % (int(100 * t / tt[-1])) + "%",
+
+ print "done."
+ return DirectoryClip(foldername, fps=fps)
+
+
+
+ def to_videofile(self, filename, fps=24, codec='libx264',
+ bitrate=None, audio=True, audio_fps=44100,
+ audio_nbytes = 2, audio_bufsize = 40000, temp_wav=None,
+ rewrite_audio = True, remove_temp = True,
+ para = True, verbose = True):
+ """
+ Makes a video file out of the clip.
+ First the clip is transformed into a directory clip, which means
+ that the frames of the future movie are computed and stored in a
+ folder as png files.
+ Then a ``DirectoryClip`` is made out of this folder and
+ transformed into a movie using ffmpeg (see DirectoryClip.to_videofile)
+
+ Returns the directory clip.
+
+ :param filename: name of the video file. Whatever the codec used,
+ it is best to write the movie name as .avi
+
+ :param fps: Frames per second in the final movie.
+
+ :param codec: Codec to use for image encoding. Can be
+ - 'rawvideo','png' : will produce a raw video, of perfect quality,
+ but possibly very huge size. 'png' is still lossless but produces
+ smaller files.
+ - 'mpeg4' : For nice quality, very well compressed videos.
+ - 'libx264' : A little better than 'mpeg4', a little heavier.
+ - Any of the (many) other codec supported by ffmpeg.
+
+ :param audio: Either ``True``, ``False``, or a file name.
+ If ``True`` and the clip has an audio clip attached, this
+ audio clip will be incorporated as a soundtrack in the movie.
+ If ``audio`` is the name of a .wav file, this wav file will
+ be incorporated as a soundtrack in the movie.
+
+ :param audiofps: frame rate to use when writing the sound.
+
+ :param temp_wav: the name of the temporary audiofile to be
+ generated and incorporated in the the movie, if any.
+
+ """
+
+ if verbose:
+ def verbose_print(s):
+ sys.stdout.write(s)
+ sys.stdout.flush()
+ else:
+ verbose_print = lambda *a : None
+
+ if isinstance(audio, str):
+ # audio is some audiofile it is maybe not a wav file. It is
+ # NOT temporary file, it will NOT be removed at the end.
+ temp_wav = audio
+ make_audio = False
+ merge_audio = True
+
+ elif self.audio is None:
+ # audio not provided as a file and no clip.audio
+ make_audio = merge_audio = False
+
+ elif audio:
+ # The audio will be the clip's audio
+ if temp_wav is None:
+ # make a name for the temporary folder
+ temp_wav = Clip._TEMP_FILES_PREFIX + "to_videofile.wav"
+
+ temp_wav = Clip._TEMP_FILES_PREFIX + "to_videofile.wav"
+ make_audio = (not os.path.exists(temp_wav)) or rewrite_audio
+ merge_audio = True
+
+ else:
+
+ make_audio = False
+ merge_audio = False
+
+ if merge_audio:
+ name, ext = os.path.splitext(os.path.basename(filename))
+ videofile = Clip._TEMP_FILES_PREFIX + "to_videofile" + ext
+ else:
+ videofile = filename
+
+
+ enough_cpu = (multiprocessing.cpu_count() > 2)
+
+ verbose_print("Making file %s ...\n"%filename)
+ if para and make_audio and enough_cpu:
+ # Parallelize
+ verbose_print("Writing audio/video in parrallel.\n")
+ audioproc = multiprocessing.Process(
+ target=self.audio.to_audiofile,
+ args=(temp_wav,audio_fps,audio_nbytes,
+ audio_bufsize,verbose))
+ audioproc.start()
+ vio.ffmpeg_write(self, videofile, fps, codec, bitrate=bitrate,
+ 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.to_audiofile(temp_wav,audio_fps, audio_nbytes,
+ audio_bufsize, verbose)
+ vio.ffmpeg_write(self, videofile, fps, codec, verbose=verbose)
+
+ # Merge with audio if any and trash temporary files.
+
+ if merge_audio:
+
+ verbose_print("\nNow merging video and audio...\n")
+ vio.ffmpeg.merge_video_audio(videofile,temp_wav,filename,
+ ffmpeg_output=False)
+ if remove_temp:
+ os.remove(videofile)
+ if not isinstance(audio,str):
+ os.remove(temp_wav)
+ verbose_print("\nYour video is ready ! Fingers crossed"+
+ " for the Oscars !")
+
+
+ def blit_on(self, picture, t):
+ """ Returns the result of the blit of the clip's frame at time `t`
+ on the given `picture`, the position of the clip being given
+ by the clip's ``pos`` attribute. Meant for compositing. """
+
+ hf, wf = sizef = picture.shape[:2]
+
+ if self.ismask and picture.max() != 0:
+ return np.maximum(picture, self.blit_on(np.zeros(sizef), t))
+
+ ct = t - self.start # clip time
+
+ # GET IMAGE AND MASK IF ANY
+
+ img = self.get_frame(ct)
+ mask = (None if (self.mask is None) else self.mask.get_frame(ct))
+ hi, wi = img.shape[:2]
+
+ # SET POSITION
+
+ pos = self.pos(ct)
+
+
+ # preprocess short writings of the position
+ if isinstance(pos,str):
+ pos = { 'center': ['center','center'],
+ 'left': ['left','center'],
+ 'right': ['right','center'],
+ 'top':['center','top'],
+ 'bottom':['center','bottom']}[pos]
+ else:
+ pos = list(pos)
+
+ # is the position relative (given in % of the clip's size) ?
+ if self.relative_pos:
+ for i, dim in enumerate(wf, hf):
+ if not isinstance(pos[i], str):
+ pos[i] = dim * pos[i]
+
+ if isinstance(pos[0], str):
+ D = {'left': 0, 'center': (wf - wi) / 2, 'right': wf - wi}
+ pos[0] = D[pos[0]]
+
+ if isinstance(pos[1], str):
+
+ D = {'top': 0, 'center': (hf - hi) / 2, 'bottom': hf - hi}
+ pos[1] = D[pos[1]]
+
+ pos = map(int, pos)
+
+ return blit(img, picture, pos, mask=mask, ismask=self.ismask)
+
+ #-----------------------------------------------------------------
+ # F I L T E R I N G
+
+
+ def subfx(self, fx, ta=0, tb=None, **kwargs):
+ """
+ Returns a new clip in which the function ``fun`` (clip->clip) has
+ been applied to the subclip between times `ta` and `tb` (in
+ seconds).
+
+ >>> # The scene between times t=3s and t=6s in ``clip`` will be
+ >>> # be played twice slower in ``newclip``
+ >>> newclip = clip.subapply(lambda c:c.speedx(0.5) , 3,6)
+
+ """
+ left = None if (ta == 0) else self.subclip(0, tb=ta)
+ center = self.subclip(ta, tb).fx(**kwargs)
+ right = None if (tb is None) else self.subclip(ta=tb)
+
+ clips = [c for c in left, center, right if c != None]
+ cc = VideoClip.concat(clips)
+
+ if self.start != None:
+ cc = cc.set_start(self.start)
+
+ return cc
+
+ # IMAGE FILTERS
+
+ def fl_image(self, image_func, applyto=[]):
+ """ Modifies the images of a clip by replacing the frame
+ `get_frame(t)` by another frame, `image_func(get_frame(t))`
+ """
+ return self.fl(lambda gf, t: image_func(gf(t)), applyto)
+
+ #--------------------------------------------------------------
+ # C O M P O S I T I N G
+
+
+ def add_mask(self, constant_size=True):
+ """
+ Returns a copy of the clip with a completely opaque mask
+ (made of ones). This makes computations slow compared to having
+ a None mask but can be useful in many cases. Choose
+
+ :param constant_size: `False` for clips with moving image size.
+ """
+ if constant_size:
+ return self.set_mask(ImClip.ColorClip(self.size, 1.0, ismask=True))
+ else:
+ mask = VideoClip(ismask=True).set_get_frame(
+ lambda t: np.ones(self.get_frame(t).shape))
+ return self.set_mask(mask)
+
+ def on_color(self, size=None, color=(0, 0, 0), pos=None, col_opacity=None):
+ """
+ Returns a clip made of the current clip overlaid on a color
+ clip of a possibly bigger size. Can serve to flatten transparent
+ clips
+
+ :param size: size of the final clip. By default it will be the
+ size of the current clip.
+ :param bg_color: the background color of the final clip
+ :param pos: the position of the clip in the final clip.
+ :param col_opacity: should the added zones be transparent ?
+ """
+ from compositing.CompositeVideoClip import CompositeVideoClip
+ if size is None:
+ size = self.size
+ if pos is None:
+ pos = 'center'
+ colorclip = ImClip.ColorClip(size, color)
+ if col_opacity:
+ colorclip = colorclip.add_mask().set_opacity(col_opacity)
+
+ return CompositeVideoClip([colorclip, self.set_pos(pos)],
+ transparent=(col_opacity != None))
+
+
+ def set_get_frame(self, gf):
+ newclip = Clip.set_get_frame(self, gf)
+ newclip.size = newclip.get_frame(0).shape[:2][::-1]
+ return newclip
+
+ def set_audio(self, audioclip):
+ """ Returns a copy of the clip with the audio set to ``audio``,
+ which must be a VideoClip. """
+ newclip = copy(self)
+ newclip.audio = audioclip
+ return newclip
+
+ def set_mask(self, mask):
+ """ Returns a copy of the clip with the mask set to ``mask``,
+ which must be a greyscale (values in 0-1) VideoClip"""
+ newclip = copy(self)
+ newclip.mask = mask
+ return newclip
+
+ def set_opacity(self, op):
+ """
+ Returns a semi-transparent copy of the clip where the mask is
+ multiplied by ``op`` (any float, normally between 0 and 1).
+ """
+ newclip = copy(self)
+ newclip.mask = self.mask.fl_image(lambda pic: op * pic)
+ return newclip
+
+ @apply_to_mask
+ def set_pos(self, pos, relative=False):
+ """
+ Sets the position that the clip will have when included
+ in compositions. The argument ``pos`` can be either a couple
+ ``(x,y)`` or a function ``t-> (x,y)``. `x` and `y` mark the
+ location of the top left corner of the clip, and can be
+ of several types:
+
+ >>> clip.set_pos((45,150)) # x=45, y=150
+ >>>
+ >>> # clip horizontally centered, at the top of the picture
+ >>> clip.set_pos(("center","top"))
+ >>>
+ >>> # clip is at 40% of the width, 70% of the height:
+ >>> clip.set_pos((0.4,0.7), relative=True)
+ >>>
+ >>> # clip's position is horizontally centered, and moving up !
+ >>> clip.set_pos(lambda t: ('center', 50+t) )
+
+ """
+
+ newclip = copy(self)
+ newclip.relative_pos = relative
+ if hasattr(pos, '__call__'):
+ newclip.pos = pos
+ else:
+ newclip.pos = lambda t: pos
+
+ return newclip
+
+ #--------------------------------------------------------------
+ # CONVERSIONS
+
+ def to_ImageClip(self,t=0):
+ """
+ Return an ImageClip made out of the clip's frame at time ``t``
+ """
+ return ImClip.ImageClip(self.get_frame(t))
+
+ def to_mask(self, canal=0):
+ """ Returns a mask a video clip made from the clip. """
+ if self.ismask:
+ return self
+ else:
+ newclip = self.fl_image(lambda pic: 1.0 * pic[:, :, canal] / 255)
+ newclip.ismask = True
+ return newclip
+
+ def to_RGB(self):
+ """
+ Returns a non-mask video clip made from the mask video clip.
+ """
+ if self.ismask:
+ newclip = self.fl_image(
+ lambda pic: np.dstack(3 * [255 * pic]).astype('uint8'))
+ newclip.ismask = False
+ return newclip
+ else:
+ return self
+
+
+ #----------------------------------------------------------------
+ # Audio
+
+ def without_audio(self):
+ """ Returns a copy of the clip with audio set to None. """
+ newclip = copy(self)
+ newclip.audio = None
+ return newclip
+
+ #-----------------------------------------------------------------
+ # Previews:
+
+try:
+ # Add methods preview and show (only if pygame installed)
+ from io.preview import show, preview
+ VideoClip.preview = preview
+ VideoClip.show = show
+except:
+ pass
diff --git a/moviepy/video/__init__.py b/moviepy/video/__init__.py
new file mode 100644
index 00000000..65d66813
--- /dev/null
+++ b/moviepy/video/__init__.py
@@ -0,0 +1,12 @@
+
+#~ from moviepy.video.VideoClip import VideoClip
+from moviepy.video.ImageClip import ImageClip, ColorClip, TextClip
+from io import VideoFileClip
+
+try:
+ import pygame as pg
+ pg.init()
+ pg.display.set_caption('MoviePy')
+except:
+ print ("WARNING: Pygame not found. Previews and many other user" +
+ " interfaces will not be enabled.")
diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.py
new file mode 100644
index 00000000..a9f3d055
--- /dev/null
+++ b/moviepy/video/compositing/CompositeVideoClip.py
@@ -0,0 +1,116 @@
+import numpy as np
+from moviepy.video.VideoClip import VideoClip
+from moviepy.video.ImageClip import ColorClip
+from moviepy.audio.AudioClip import CompositeAudioClip
+
+# CompositeVideoClip
+
+class CompositeVideoClip(VideoClip):
+
+ """
+
+ A VideoClip made of other videoclips displayed together. This is the
+ base class for most compositions.
+
+ :param 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:
+
+ - The attribute ``pos`` determines where the clip is placed.
+ See ``VideoClip.set_pos``
+ - 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
+
+ :param 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.
+
+ """
+
+ def __init__(self, clips, size=None, bg_color=None, transparent=False,
+ ismask=False):
+
+ if size is None:
+ size = clips[0].size
+
+ if bg_color is None:
+ bg_color = 0.0 if ismask else (0, 0, 0)
+
+ VideoClip.__init__(self)
+
+ self.size = size
+ self.ismask = ismask
+ self.clips = clips
+ self.transparent = transparent
+ self.bg_color = bg_color
+ self.bg = ColorClip(size, col=self.bg_color).get_frame(0)
+
+ # compute duration
+ ends = [c.end for c in self.clips]
+ if not any([(e is None) for e in ends]):
+ self.duration = max(ends)
+
+ # compute audio
+ audioclips = [v.audio for v in self.clips if v.audio != None]
+ if len(audioclips) > 0:
+ self.audio = CompositeAudioClip(audioclips)
+
+ # compute mask
+ if transparent:
+ maskclips = [c.mask.set_pos(c.pos) for c in self.clips]
+ self.mask = CompositeVideoClip(maskclips,self.size,
+ transparent=False, ismask=True)
+
+ def gf(t):
+ """ The clips playing at time `t` are blitted over one
+ another. """
+
+ f = self.bg
+ for c in self.playing_clips(t):
+ f = c.blit_on(f, t)
+ return f
+
+ self.get_frame = gf
+
+ def playing_clips(self, t=0):
+ """ Returns a list of the clips in the composite clips that are
+ actually playing at the given time `t`. """
+ return [c for c in self.clips if c.is_playing(t)]
+
+def clips_array(array, rows_widths=None, cols_widths=None,
+ transparent = True, bg_color = (0,0,0)):
+
+ array = np.array(array)
+ sizes_array = np.vectorize(lambda c:c.size)(array)
+ if rows_widths == None:
+ rows_widths = sizes_array.max(axis=0)
+ if cols_widths == None:
+ cols_widths = sizes_array.max(axis=1)
+
+ xx = np.cumsum([0]+list(cols_width))
+ yy = np.cumsum([0]+list(rows_width))
+
+ for j,(x,rw) in enumerate(zip(xx,cols_width)):
+ for i,(y,cw) in enumerate(zip(yy,cols_width)):
+ clip = array[i,j]
+ w,h = clip.size
+ if (w < cw) or (h < rw):
+ clip = CompositeClip([clip], size = (cw,rw),
+ transparent = True, bg_color = (0,0,0))
+ array[i,j] = clip.set_pos((x,y))
+
+
+ return CompositeVideoClip(array.flatten(),
+ size = (xx[-1],yy[-1]))
+
+
diff --git a/moviepy/video/compositing/__init__.py b/moviepy/video/compositing/__init__.py
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/moviepy/video/compositing/__init__.py
@@ -0,0 +1 @@
+
diff --git a/moviepy/video/compositing/concatenate.py b/moviepy/video/compositing/concatenate.py
new file mode 100644
index 00000000..5ce9eb7d
--- /dev/null
+++ b/moviepy/video/compositing/concatenate.py
@@ -0,0 +1,90 @@
+import numpy as np
+
+
+from moviepy.video.VideoClip import VideoClip
+from CompositeVideoClip import CompositeVideoClip
+from moviepy.audio.AudioClip import CompositeAudioClip
+
+from on_color import on_color
+
+def concatenate(clipslist, method = 'chain', transition=None,
+ bg_color=(0, 0, 0), transparent=False, ismask=False, crossover = 0):
+ """
+
+ Returns a video clip made by clip by concatenating several video clips.
+ (Concatenated means that they will be played one after another).
+ 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.
+
+ :param clipslist: a list of video clips which must all have
+ their ``duration`` attributes set.
+ :param transition: a clip that will be played between each two
+ clips of the list.
+ :param bg_color: color of the background ()
+ :param 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.
+
+ :ivar start_times (list): ``start_times[i]`` gives the time at which
+ the i-th clip starts playing.
+
+
+ """
+
+ if transition != None:
+ l = [[v, transition] for v in clipslist[:-1]]
+ clipslist = reduce(lambda x, y: x + y, l) + [clipslist[-1]]
+ transition = None
+
+ tt = np.cumsum([0] + [c.duration for c in clipslist])
+ sizes = [v.size for v in clipslist]
+ w = max([r[0] for r in sizes])
+ h = max([r[1] for r in sizes])
+
+ if method == 'chain':
+ result = VideoClip(ismask = ismask)
+ result.size = (w,h)
+ def gf(t):
+ i = max([i for i, e in enumerate(tt) if e <= t])
+ return clipslist[i].get_frame(t - tt[i])
+ result.get_frame = gf
+ if (len(sizes)>1) and (bg_color !=None):
+ result = result.fx( on_color, (w,h), bg_color, 'center')
+
+ elif method == 'compose':
+ tt = np.maximum(0, tt - crossover*np.arange(len(tt)))
+ 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)
+
+ result.start_times = tt[:-1]
+ result.duration = tt[-1]
+
+ # Compute the mask if any
+
+ if transparent and (not ismask):
+ # add a mask to the clips which have none
+ clips_withmask = [(c if (c.mask!=None) else c.add_mask())
+ for c in clipslist]
+ result.mask = ConcatVideoClip([c.mask for c in clips_withmask],
+ bg_color=0, ismask=True)
+
+
+ # Compute the audio, if any.
+
+ audio_t = [(c.audio,t) for c,t in zip(clipslist,tt) if c.audio!=None]
+ print audio_t
+ if len(audio_t)>0:
+ result.audio = CompositeAudioClip([a.set_start(t)
+ for a,t in audio_t])
+ return result
diff --git a/moviepy/video/compositing/on_color.py b/moviepy/video/compositing/on_color.py
new file mode 100644
index 00000000..ad180614
--- /dev/null
+++ b/moviepy/video/compositing/on_color.py
@@ -0,0 +1,26 @@
+from moviepy.video.ImageClip import ColorClip
+from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
+
+def on_color(clip, size=None, color=(0, 0, 0), pos=None, col_opacity=None):
+ """
+ Returns a clip made of the current clip overlaid on a color
+ clip of a possibly bigger size. Can serve to flatten transparent
+ clips (ideal for previewing clips with masks).
+
+ :param size: size of the final clip. By default it will be the
+ size of the current clip.
+ :param bg_color: the background color of the final clip
+ :param pos: the position of the clip in the final clip.
+ :param col_opacity: should the added zones be transparent ?
+ """
+
+ if size is None:
+ size = clip.size
+ if pos is None:
+ pos = 'center'
+ colorclip = ColorClip(size, color)
+ if col_opacity:
+ colorclip = colorclip.with_mask().set_opacity(col_opacity)
+
+ return CompositeVideoClip([colorclip, clip.set_pos(pos)],
+ transparent=(col_opacity != None))
diff --git a/moviepy/video/compositing/positioning.py b/moviepy/video/compositing/positioning.py
new file mode 100644
index 00000000..572ea86a
--- /dev/null
+++ b/moviepy/video/compositing/positioning.py
@@ -0,0 +1,8 @@
+"""
+This module provides classes that make positioning easy
+"""
+
+
+class ClipPosition:
+
+
diff --git a/moviepy/video/compositing/transitions.py b/moviepy/video/compositing/transitions.py
new file mode 100644
index 00000000..f9979dcb
--- /dev/null
+++ b/moviepy/video/compositing/transitions.py
@@ -0,0 +1,28 @@
+"""
+Don't abuse transitions ! Here is the current catalogue. These are meant
+to be used with clip.fx
+"""
+
+from moviepy.decorators import requires_duration
+
+from moviepy.video.fx import fadein, fadeout
+
+def crossfadein(clip, duration):
+ """
+ Makes the clip appear progressively, over ``duration`` seconds.
+ Only works when the clip is included in a CompositeVideoClip.
+ """
+ newclip = clip.copy()
+ newclip.mask = clip.mask.fx(fadein, duration)
+ return newclip
+
+
+@requires_duration
+def crossfadeout(clip, duration):
+ """
+ Makes the clip disappear progressively, over ``duration`` seconds.
+ Only works when the clip is included in a CompositeVideoClip.
+ """
+ newclip = clip.copy()
+ newclip.mask = clip.mask.fx(fadeout, duration)
+ return newclip
diff --git a/moviepy/video/fx/__init__.py b/moviepy/video/fx/__init__.py
new file mode 100644
index 00000000..b3fda558
--- /dev/null
+++ b/moviepy/video/fx/__init__.py
@@ -0,0 +1,14 @@
+"""
+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/blackwhite.py b/moviepy/video/fx/blackwhite.py
new file mode 100644
index 00000000..bb9f9f4b
--- /dev/null
+++ b/moviepy/video/fx/blackwhite.py
@@ -0,0 +1,8 @@
+
+def blackwhite(clip, RGB = [1,1,1], preserve_luminosity=True):
+ """ Desaturates the picture, makes it black and white.
+ method = sum (TODO: others) """
+ if RGB == 'CRT_phosphor':
+ RGB = [0.2125, 0.7154, 0.0721]
+
+ return clip.fl_image(lambda im: np.dtack(3*[im.sum(axis=2)/3]) )
diff --git a/moviepy/video/fx/blink.py b/moviepy/video/fx/blink.py
new file mode 100644
index 00000000..9919f3ce
--- /dev/null
+++ b/moviepy/video/fx/blink.py
@@ -0,0 +1,12 @@
+def blink(clip, d_on, d_off):
+ """
+ Makes the clip blink. At each blink it will be displayed ``d_on``
+ seconds and disappear ``d_off`` seconds. Will only work in
+ composite clips.
+ """
+ newclip = copy(clip)
+ if newclip.mask is None:
+ newclip = newclip.with_mask()
+ D = d_on + d_off
+ newclip.mask = newclip.mask.fl( lambda gf,t: gf(t)*((t % D) < d_on))
+ return newclip
diff --git a/moviepy/video/fx/colorx.py b/moviepy/video/fx/colorx.py
new file mode 100644
index 00000000..d402e63c
--- /dev/null
+++ b/moviepy/video/fx/colorx.py
@@ -0,0 +1,9 @@
+import numpy as np
+
+def colorx(clip, factor):
+ """ multiplies the clip's colors by the given factor, can be used
+ to decrease or increase the clip's brightness (is that the
+ reight word ?)
+ """
+ return clip.fl_image( lambda pic: np.minimum(255,(factor*pic)).
+ astype('uint8'))
diff --git a/moviepy/video/fx/crop.py b/moviepy/video/fx/crop.py
new file mode 100644
index 00000000..d81911e1
--- /dev/null
+++ b/moviepy/video/fx/crop.py
@@ -0,0 +1,7 @@
+def crop(clip, x1=0, y1=0, x2=None, y2=None):
+ if x2 is None:
+ x2 = clip.size[0]
+ if y2 is None:
+ y2 = clip.size[1]
+ return clip.fl_image(lambda pic: pic[y1:y2, x1:x2],
+ applyto=['mask'])
diff --git a/moviepy/video/fx/fadein.py b/moviepy/video/fx/fadein.py
new file mode 100644
index 00000000..4bb204a0
--- /dev/null
+++ b/moviepy/video/fx/fadein.py
@@ -0,0 +1,8 @@
+
+def fadein(clip, duration):
+ """
+ Makes the clip fade to black progressively, over ``duration`` seconds.
+ For more advanced fading, see ``composition.crossfade``
+ """
+
+ return clip.fl(lambda gf, t: min(1.0 * t / duration, 1) * gf(t))
diff --git a/moviepy/video/fx/fadeout.py b/moviepy/video/fx/fadeout.py
new file mode 100644
index 00000000..b34bc5c3
--- /dev/null
+++ b/moviepy/video/fx/fadeout.py
@@ -0,0 +1,15 @@
+from moviepy.decorators import requires_duration
+
+@requires_duration
+def fadeout(clip, duration):
+ """
+ Makes the clip fade to black progressively, over ``duration`` seconds.
+ For more advanced fading, see ``composition.crossfade``
+ """
+ fading = lambda t: min(1.0 * (clip.duration - t) / duration, 1)
+ return clip.fl(lambda gf, t: fading(t) * gf(t))
+
+
+
+
+
diff --git a/moviepy/video/fx/headblur.py b/moviepy/video/fx/headblur.py
new file mode 100644
index 00000000..c4eda360
--- /dev/null
+++ b/moviepy/video/fx/headblur.py
@@ -0,0 +1,37 @@
+import cv2
+import numpy as np
+
+def headblur(clip,fx,fy,r_zone,r_blur=None):
+ """
+ Returns a filter that will blurr a moving part (a head ?) of
+ the frames. The position of the blur at time t is
+ defined by (fx(t), fy(t)), the radius of the blurring
+ by ``r_zone`` and the intensity of the blurring by ``r_blur``.
+ Requires OpenCV for the circling and the blurring.
+ Automatically deals with the case where part of the image goes
+ offscreen.
+ """
+
+ if r_blur==None: r_blur = 2*r_zone/3
+
+ def fl(gf,t):
+
+ im = gf(t)
+ h,w,d = im.shape
+ x,y = int(fx(t)),int(fy(t))
+ x1,x2 = max(0,x-r_zone),min(x+r_zone,w)
+ y1,y2 = max(0,y-r_zone),min(y+r_zone,h)
+ region_size = y2-y1,x2-x1
+
+ mask = np.zeros(region_size).astype('uint8')
+ cv2.circle(mask, (r_zone,r_zone), r_zone, 255, -1,
+ lineType=cv2.CV_AA)
+
+ mask = np.dstack(3*[(1.0/255)*mask])
+
+ orig = im[y1:y2, x1:x2]
+ blurred = cv2.blur(orig,(r_blur, r_blur))
+ im[y1:y2, x1:x2] = mask*blurred + (1-mask)*orig
+ return im
+
+ return clip.fl(fl)
diff --git a/moviepy/video/fx/loop.py b/moviepy/video/fx/loop.py
new file mode 100644
index 00000000..20dce02f
--- /dev/null
+++ b/moviepy/video/fx/loop.py
@@ -0,0 +1,14 @@
+from moviepy.decorators import (apply_to_mask,
+ apply_to_audio,
+ requires_duration)
+
+
+@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)
diff --git a/moviepy/video/fx/margin.py b/moviepy/video/fx/margin.py
new file mode 100644
index 00000000..7384e73d
--- /dev/null
+++ b/moviepy/video/fx/margin.py
@@ -0,0 +1,44 @@
+import numpy as np
+from moviepy.decorators import apply_to_mask
+
+
+@apply_to_mask
+def margin(clip, mar=None, left=0, right=0, top=0,
+ bottom=0, color=(0, 0, 0), opacity = 1.0):
+ """
+ Draws an external margin all around the frame.
+
+ :param mar: if not ``None``, then the new clip has a margin of
+ size ``mar`` in pixels on the left, right, top, and bottom.
+
+ :param left, right, top, bottom: width of the margin in pixel
+ in these directions.
+
+ :param color: color of the margin.
+
+ :param mask_margin: value of the mask on the margin. Setting
+ this value to 0 yields transparent margins.
+
+ """
+
+ if (opacity != 1.0) and (clip.mask is None) and not (clip.ismask):
+ clip = clip.add_mask()
+
+ if mar != None:
+ left = right = top = bottom = mar
+
+ new_w, new_h = clip.w + left + right, clip.h + top + bottom
+
+ if clip.ismask:
+ shape = (new_h, new_w)
+ bg = np.tile(opacity, (new_h, new_w)).reshape(shape)
+ else:
+ shape = (new_h, new_w, 3)
+ bg = np.tile(color, (new_h, new_w)).reshape(shape)
+
+ def fl(pic):
+ im = +bg
+ im[top:top + clip.h, left:left + clip.w] = pic
+ return im
+
+ return clip.fl_image(fl)
diff --git a/moviepy/video/fx/painting.py b/moviepy/video/fx/painting.py
new file mode 100644
index 00000000..bcd62d53
--- /dev/null
+++ b/moviepy/video/fx/painting.py
@@ -0,0 +1,35 @@
+painting_possible = True
+try:
+ from skimage.filter import sobel
+except:
+ try:
+ from scipy.ndimage.filters import sobel
+ except:
+ painting_possible = False
+
+
+import numpy as np
+
+def to_painting(image,saturation = 1.4,black = 0.006):
+ """ transforms any photo into some kind of painting """
+ edges = sobel(image.mean(axis=2))
+ darkening = black*(255*np.dstack(3*[edges]))
+ painting = saturation*image-darkening
+ return np.maximum(0,np.minimum(255,painting)).astype('uint8')
+
+def painting(clip, saturation = 1.4,black = 0.006):
+ """
+ Transforms any photo into some kind of painting. Saturation
+ tells at which point the colors of the result should be
+ flashy. ``black`` gives the anount of black lines wanted.
+ Requires Scikit-image or Scipy installed.
+ """
+ return clip.fl_image(lambda im : to_painting(im,saturation,black))
+
+
+if not painting_possible:
+ doc = painting.__doc__
+ def painting(clip, newsize=None, height=None, width=None):
+ raise IOError("fx painting needs scikit-image or scipy")
+
+ painting.__doc__ = doc
diff --git a/moviepy/video/fx/resize.py b/moviepy/video/fx/resize.py
new file mode 100644
index 00000000..d4c3a78c
--- /dev/null
+++ b/moviepy/video/fx/resize.py
@@ -0,0 +1,92 @@
+
+resize_possible = True
+
+try:
+ import cv2
+ resizer = lambda pic, newsize : cv2.resize(pic.astype('uint8'),
+ tuple(map(int, newsize)),
+ interpolation=cv2.INTER_AREA)
+except:
+ try:
+ import Image
+ def resizer(pic, newsize):
+ newsize = map(int, newsize)[::-1]
+ shape = pic.shape
+ newshape = (newsize[0],newsize[2],shape[1])
+ pilim = Image.fromarray(pic)
+ resized_pil = pilim.resize(newsize, Image.ANTIALIAS)
+ arr = np.fromstring(resized_pil.tostring(), dtype='uint8')
+ return arr.reshape(newshape)
+ except:
+ try:
+ import scipy.misc.imresize as imresize
+ resizer = lambda pic, newsize : imresize(pic,
+ map(int, newsize[::-1]))
+ except:
+ resize_possible = False
+
+
+from moviepy.decorators import apply_to_mask
+
+@apply_to_mask
+def resize(clip, newsize=None, height=None, width=None):
+ """
+ Returns a video clip that is a resized version of the clip.
+
+ :param newsize: can be either ``(height,width)`` in pixels or
+ a float representing a scaling factor. Or a function of time
+ returning one of these.
+
+ :param width: width of the new clip in pixel. The height is
+ then computed so that the width/height ratio is conserved.
+
+ :param height: height of the new clip in pixel. The width is
+ then computed so that the width/height ratio is conserved.
+
+ >>> myClip.resize( (460,720) ) # New resolution: (460,720)
+ >>> myClip.resize(0.6) # width and heigth multiplied by 0.6
+ >>> myClip.resize(width=800) # height computed automatically.
+ >>> myClip.resize(lambda t : 1+0.02*t) # slow swelling of the clip
+
+ """
+ w, h = clip.size
+
+ if newsize != None:
+ def trans_newsize(ns):
+ if isinstance(ns, (int, float)):
+ return [ns * w, ns * h]
+ else:
+ return ns
+ if hasattr(newsize, "__call__"):
+ newsize = lambda t : trans_newsize(newsize(t))
+ if clip.ismask:
+ fl = lambda gf,t: 1.0*resizer((255 * gf(t)).astype('uint8'),
+ newsize(t))/255
+ else:
+ fl = lambda gf,t: resizer(gf(t).astype('uint8'),newsize(t))
+
+ return clip.fl(fl)
+
+ else:
+ newsize = trans_newsize(newsize)
+
+
+ elif height != None:
+ newsize = [w * height / h, height]
+ elif width != None:
+ newsize = [width, h * width / w]
+
+ if clip.ismask:
+ fl = lambda pic: 1.0*resizer((255 * pic).astype('uint8'),
+ newsize)/255
+ else:
+ fl = lambda pic: resizer(pic.astype('uint8'), newsize)
+
+ return clip.fl_image(fl)
+
+
+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")
+ resize.__doc__ = doc
diff --git a/moviepy/video/fx/scroll.py b/moviepy/video/fx/scroll.py
new file mode 100644
index 00000000..d99b5167
--- /dev/null
+++ b/moviepy/video/fx/scroll.py
@@ -0,0 +1,11 @@
+
+def scroll(clip, h=None, w=None, x_speed=0, y_speed=0, apply_to="mask"):
+ """ Scrolls horizontally or vertically a clip, e.g. to make end
+ credits """
+ if h is None: h = clip.h
+ if w is None: w = clip.w
+ def f(gf,t):
+ x = int(x_speed*t)
+ y = int(y_speed*t)
+ return gf(t)[y:y+h, x:x+w]
+ return clip.fl(fl, apply_to = apply_to)
diff --git a/moviepy/video/fx/speedx.py b/moviepy/video/fx/speedx.py
new file mode 100644
index 00000000..b83580ba
--- /dev/null
+++ b/moviepy/video/fx/speedx.py
@@ -0,0 +1,15 @@
+from moviepy.decorators import apply_to_mask,apply_to_audio
+
+@apply_to_mask
+@apply_to_audio
+def speedx(self, factor):
+ """
+ Returns a clip playing the current clip but at a speed multiplied
+ by ``factor``.
+ The same effect is applied to the clip's audio and mask if any.
+ """
+ newclip = self.fl_time(lambda t: factor * t)
+ if self.duration != None:
+ return newclip.set_duration(1.0 * self.duration / factor)
+ else:
+ return newclip
diff --git a/moviepy/video/fx/time_mirror.py b/moviepy/video/fx/time_mirror.py
new file mode 100644
index 00000000..75350270
--- /dev/null
+++ b/moviepy/video/fx/time_mirror.py
@@ -0,0 +1,25 @@
+from moviepy.decorators import (apply_to_mask, apply_to_audio,
+ requires_duration)
+
+
+@requires_duration
+@apply_to_mask
+@apply_to_audio
+def time_mirror(self):
+ """
+ Returns a clip that plays the current clip backwards.
+ The clip must have its ``duration`` attribute set.
+ The same effect is applied to the clip's audio and mask if any.
+ """
+ return self.fl_time(lambda t: self.duration - t, keep_duration=True)
+
+
+@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)
diff --git a/moviepy/video/fx/xmirror.py b/moviepy/video/fx/xmirror.py
new file mode 100644
index 00000000..9f41ef4a
--- /dev/null
+++ b/moviepy/video/fx/xmirror.py
@@ -0,0 +1,3 @@
+def xmirror(clip, apply_to= "mask"):
+ """ flips the clip horizontally (and its mask too, by default) """
+ return clip.fl_image(gf(t)[:,::-1], apply_to = apply_to)
diff --git a/moviepy/video/fx/ymirror.py b/moviepy/video/fx/ymirror.py
new file mode 100644
index 00000000..99db3764
--- /dev/null
+++ b/moviepy/video/fx/ymirror.py
@@ -0,0 +1,3 @@
+def ymirror(clip, apply_to= "mask"):
+ """ flips the clip horizontally (and its mask too, by default) """
+ return clip.fl_image(gf(t)[::-1], apply_to = apply_to)
diff --git a/moviepy/video/io/DirectoryClip.py b/moviepy/video/io/DirectoryClip.py
new file mode 100644
index 00000000..a25cd065
--- /dev/null
+++ b/moviepy/video/io/DirectoryClip.py
@@ -0,0 +1,85 @@
+ """
+
+ A VideoClip read from a directory containing pictures.
+ Still experimental and subject to changes.
+
+ """
+
+ def __init__(self, foldername, fps, transparent=True, ismask=False):
+
+ VideoClip.__init__(self, ismask=ismask)
+
+ self.directory = foldername
+ self.fps = fps
+ allfiles = os.listdir(foldername)
+ self.pics = sorted(["%s/%s" % (foldername, f) for f in allfiles
+ if not f.endswith(('.txt','.wav'))])
+
+ audio = [f for f in allfiles if f.endswith('.wav')]
+
+ if len(audio) > 0:
+ self.audio = AudioFileClip(audio[0])
+ self.audiofile =audio[0]
+
+ self.size = imread(self.pics[0]).shape[:2][::-1]
+
+ if imread(self.pics[0]).shape[2] == 4: # transparent png
+
+ if ismask:
+ def get_frame(t):
+ return 1.0 * imread(self.pics[int(self.fps * t)])[:, :, 3] / 255
+ else:
+ def get_frame(t):
+ return imread(self.pics[int(self.fps * t)])[:, :, :2]
+
+ if transparent:
+ self.mask = DirectoryClip(foldername, fps, ismask=True)
+
+ else:
+
+ def get_frame(t):
+ return imread(self.pics[int(self.fps * t)])
+
+ self.get_frame = get_frame
+ self.duration = 1.0 * len(self.pics) / self.fps
+
+ def to_videofile(self, filename, bitrate=3000, audio=True):
+ """
+ Transforms the directory clip into a movie using ffmpeg.
+ Uses the framerate specified by ``clip.fps``.
+
+ :param filename: name of the video file to write in, like
+ 'myMovie.ogv' or 'myFilm.mp4'.
+ :param bitrate: final bitrate of the video file (in kilobytes/s).
+ 3000-6000 gives generally light files and an acceptable quality.
+ :param audio: the name of an audiofile to be incorporated in the
+ the movie.
+ """
+
+ if audio != None:
+ # if there is audio, then ``videofile`` is a temporary file
+ # that will then be merged with audio and removed.
+ name, ext = os.path.splitext(os.path.basename(filename))
+ videofile = Clip._TEMP_FILES_PREFIX + name + ext
+ else:
+ videofile = filename
+
+ cmd = ["ffmpeg", "-y", "-f", "image2",
+ "-r","%d"%self.fps,
+ "-i", os.path.join(self.directory,self.directory,"%06d.png"),
+ "-b", "%dk"%bitrate,
+ "-r", "%d"%self.fps, videofile]
+
+ print "running : "+ " ".join(cmd)
+ subprocess.call(cmd)
+
+ if audio:
+ # Merge video and audio, and remove temporary files
+ subprocess.call(["ffmpeg", "-y",
+ "-i", self.audiofile +
+ "-i", videofile,
+ "-strict experimental", filename])
+
+ print "running: %s" % cmd
+ os.system(cmd)
+ os.remove(videofile)
diff --git a/moviepy/video/io/VideoFileClip.py b/moviepy/video/io/VideoFileClip.py
new file mode 100644
index 00000000..da139fd3
--- /dev/null
+++ b/moviepy/video/io/VideoFileClip.py
@@ -0,0 +1,68 @@
+import os
+
+from moviepy.video.VideoClip import VideoClip
+from moviepy.audio.io.AudioFileClip import AudioFileClip
+from moviepy.Clip import Clip
+from readers import FFMPEG_VideoReader
+
+class VideoFileClip(VideoClip):
+
+ """
+
+ A video clip originating from a movie file. For instance:
+
+ >>> clip = VideofileClip("myHolidays.mp4")
+ >>> clip2 = VideofileClip("myMaskVideo.avi",ismask = True)
+
+ :param filename: Any video file: .ogv, .mp4, .mpeg, .avi, .mov etc.
+ :param ismask: `True` if the clip is a mask.
+ :param has_mask: 'True' if there is a mask included in the videofile.
+ Commonly, video files don't have mask, but you can save the mask
+ for the videos that you make with MoviePy (see the doc from
+ ``VideoClip.to_videofile`` for more details).
+ :param audio: If `True`, then the audio is extracted from the video
+ file, in wav format, and it attributed to the clip.
+
+ :ivar filename: Name of the original video file
+ :ivar fps: Frames per second in the original file.
+
+ """
+
+ def __init__(self, filename, ismask=False, has_mask=False,
+ audio=True, audio_buffersize = 200000,
+ audio_fps=44100, audio_nbytes=2, verbose=False):
+
+ VideoClip.__init__(self, ismask)
+
+ # We store the construction parameters in case we need to make
+ # a copy (a 'co-reader').
+
+ self.parameters = {'filename':filename, 'ismask':ismask,
+ 'has_mask':has_mask, 'audio':audio,
+ 'audio_buffersize':audio_buffersize}
+
+ # Make a reader
+ pix_fmt= "rgba" if has_mask else "rgb24"
+ self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
+
+ # Make some of the reader's attributes accessible from the clip
+ self.duration = self.reader.duration
+ self.fps = self.reader.fps
+ self.size = self.reader.size
+ self.get_frame = lambda t: self.reader.get_frame(t)
+
+ # Make a reader for the audio, if any.
+ if audio:
+ try:
+ self.audio = AudioFileClip(filename, buffersize= audio_buffersize,
+ fps = audio_fps, nbytes = audio_nbytes)
+ except:
+ if verbose:
+ print "No audio found in %s"%filename
+ pass
+
+ def coreader(self, audio=True):
+ """ Returns a copy of the AudioFileClip, i.e. a new entrance point
+ to the video file. Use copy when you have different clips
+ watching the same video file at different times. """
+ return VideoFileClip(**self.parameters)
diff --git a/moviepy/video/io/__init__.py b/moviepy/video/io/__init__.py
new file mode 100644
index 00000000..cdcd657c
--- /dev/null
+++ b/moviepy/video/io/__init__.py
@@ -0,0 +1,8 @@
+"""
+Classes and methods for reading, writing and previewing video files.
+"""
+
+import ffmpeg
+
+from writers import ffmpeg_write, write_image
+from readers import FFMPEG_VideoReader
diff --git a/moviepy/video/io/ffmpeg.py b/moviepy/video/io/ffmpeg.py
new file mode 100644
index 00000000..ea2ac5be
--- /dev/null
+++ b/moviepy/video/io/ffmpeg.py
@@ -0,0 +1,104 @@
+""" Very experimental 'bindings' to ffmpeg and ImageMagick."""
+
+import os
+import sys
+import subprocess as sp
+
+
+import decorator
+
+
+def subprocess_call(f, *a, **k):
+ """
+ executes the outputed subprocess command
+ """
+ cmd = f(*a, **k)
+ sys.stdout.write( "\nRunning:\n>>> "+ " ".join(cmd))
+ sys.stdout.flush()
+ proc = sp.Popen(cmd, stdout=sp.PIPE, stdin = sp.PIPE, stderr = sp.PIPE)
+ proc.wait()
+ if proc.returncode:
+ sys.stdout.write( "WARNING: this command failed.")
+ else:
+ sys.stdout.write( "\n... ffmpeg command successful.\n")
+ sys.stdout.flush()
+
+@subprocess_call
+def movie_from_frames(filename, folder, fps, digits=6):
+ """ Writes a movie out of the frames (picture files) in a folder """
+ s = "%" + "%02d" % digits + "d.png"
+ return ["ffmpeg", "-y", "-f","image2",
+ "-r", "%d"%fps,
+ "-i", os.path.join(folder,folder) + '/' + s,
+ "-b", "%dk"%bitrate,
+ "-r", "%d"%self.fps,
+ filename]
+
+@subprocess_call
+def extract_subclip(filename, t1, t2, targetname=None):
+ """ makes a new video file playing video file ``filename`` between
+ the times ``t1`` and ``t2``. """
+ name,ext = os.path.splitext(filename)
+ if not targetname:
+ T1, T2 = [int(1000*t) for t in [t1, t2]]
+ targetname = name+ "%sSUB%d_%d.%s"(name, T1, T2, ext)
+
+ return ["ffmpeg","-y",
+ "-i", filename,
+ "-ss", "%0.2f"%t1,
+ "-t", "%0.2f"%(t2-t1),
+ "-vcodec", "copy", "-acodec", "copy", targetname]
+
+
+@subprocess_call
+def merge_video_audio(video,audio,output, acodec='libvorbis',
+ ffmpeg_output=False):
+ """ merges video file ``video`` and audio file ``audio`` into one
+ movie file ``output``. """
+ return ["ffmpeg", "-y", "-i", audio,"-i", video,
+ "-vcodec", "copy",
+ "-acodec", acodec, output]
+
+
+@subprocess_call
+def gif_to_directory(gif_file,dirName=None):
+ """
+ Stores all the frames of the given .gif file
+ into the directory ``dirName``. If ``dirName``
+ is not provided, the directory has the same name
+ as the .gif file. Supports transparency.
+ Returns the directory name.
+
+ Example:
+
+ >>> d = gif_to_directory("animated-earth.gif")
+ >>> clip = DirectoryClip(d,fps=3)
+
+ """
+
+ if dirName is None:
+ name, ext = os.path.splitext(gif_file)
+ dirName = name
+
+ try:
+ os.mkdir(dirName)
+ except:
+ pass
+
+ return ["convert", "-coalesce", gif_file,
+ os.path.join(dirName,"%04d.png")]
+
+@subprocess_call
+def extract_audio(inputfile,output,bitrate=3000,fps=44100):
+ """ extract the sound from a video file and save it in ``output`` """
+ return ["ffmpeg", "-y", "-i", inputfile, "-ab", "%dk"%bitrate,
+ "-ar", "%d"%fps, output]
+
+@subprocess_call
+def resize(video,output,size):
+ """ resizes ``video`` to new size ``size`` and write the result
+ in file ``output``. """
+ return ["ffmpeg", "-i", video, "-vf", "scale=%d:%d"%(res[0], res[1]),
+ output]
+
diff --git a/moviepy/video/io/preview.py b/moviepy/video/io/preview.py
new file mode 100644
index 00000000..fedbf992
--- /dev/null
+++ b/moviepy/video/io/preview.py
@@ -0,0 +1,105 @@
+from moviepy.decorators import requires_duration
+import threading
+import time
+import pygame as pg
+import numpy as np
+
+
+def imdisplay(imarray, screen=None):
+ """ splashes the given image array on the given pygame screen """
+ a = pg.surfarray.make_surface(imarray.swapaxes(0, 1))
+ if screen == None:
+ screen = pg.display.set_mode(imarray.shape[:2][::-1])
+ screen.blit(a, (0, 0))
+ pg.display.flip()
+
+
+def show(clip, t=0, with_mask=True):
+ """
+ Splashes the frame of clip corresponding to time ``t``.
+
+ :param t: time in seconds of the frame to display.
+
+ :param with_mask: ``False`` if the clip has a mask but you
+ want to see the clip without the mask.
+
+ """
+
+ if clip.ismask:
+ clip = clip.to_RGB()
+ if with_mask and (clip.mask != None):
+ from moviepy.video.compositing import CompositeVideoClip
+ clip = CompositeVideoClip([clip])
+ imdisplay(clip.get_frame(t))
+
+
+@requires_duration
+def preview(clip, fps=15, audio=True, audio_fps=22050,
+ audio_buffersize=10000, audio_nbytes=2):
+ """
+ Displays the clip in a window, at the given frames per second
+ (of movie) rate. It will avoid that the clip be played faster
+ than normal, but it cannot avoid the clip to be played slower
+ than normal if the computations are complex. In this case, try
+ reducing the ``fps``.
+
+ :param fps: Number of frames per second to be displayed.
+
+ :param audio: ``True`` (default) if you want the clip's audio
+ to be played in playback. The synchronization is not garanteed.
+
+ :param audiofps: The frames per second to use when generating the
+ audio sound. The lower, the cheaper the sound will be.
+
+ """
+
+ import pygame as pg
+
+ if clip.ismask:
+ clip = clip.to_RGB()
+
+ # compute and splash the first image
+ screen = pg.display.set_mode(clip.size)
+
+ audio = audio and (clip.audio != None)
+
+ if audio:
+ # the sound will be played in parrallel. We are not
+ # parralellizing it on different CPUs because it seems that
+ # pygame and openCV already use several cpus it seems.
+
+ # two synchro-flags to tell whether audio and video are ready
+ videoFlag = threading.Event()
+ audioFlag = threading.Event()
+ # launch the thread
+ audiothread = threading.Thread(target=clip.audio.preview,
+ args = (audio_fps,audio_buffersize, audio_nbytes,
+ audioFlag, videoFlag))
+ audiothread.start()
+
+ img = clip.get_frame(0)
+ imdisplay(img, screen)
+ if audio: # synchronize with audio
+ videoFlag.set() # say to the audio: video is ready
+ audioFlag.wait() # wait for the audio to be ready
+
+ t0 = time.time()
+ for t in np.arange(1.0 / fps, clip.duration, 1.0 / fps):
+
+ img = clip.get_frame(t)
+
+ for event in pg.event.get():
+ if event.type == pg.KEYDOWN:
+ if (event.key == pg.K_ESCAPE):
+ pg.mixer.quit()
+ print "Keyboard interrupt"
+ return
+
+ elif event.type == pg.MOUSEBUTTONDOWN:
+ x,y = pg.mouse.get_pos()
+ rgb = img[x,y]
+ print "time, position, color : ", t,(x,y),rgb
+
+ t1 = time.time()
+ time.sleep(max(0, t - (t1-t0)) )
+ imdisplay(img, screen)
diff --git a/moviepy/video/io/readers.py b/moviepy/video/io/readers.py
new file mode 100644
index 00000000..d5b97718
--- /dev/null
+++ b/moviepy/video/io/readers.py
@@ -0,0 +1,156 @@
+import subprocess as sp
+import re
+import time
+
+import numpy as np
+from moviepy.conf import FFMPEG_BINARY
+from moviepy.tools import cvsecs
+
+
+
+
+class FFMPEG_VideoReader:
+
+ def __init__(self, filename, print_infos=False, pix_fmt="rgb24"):
+
+ self.filename = filename
+ self.pix_fmt = pix_fmt
+ self.initialize()
+ self.depth = 4 if pix_fmt=="rgba" else 3
+ self.load_infos(print_infos)
+ self.pos = 1
+ self.lastread = self.read_frame()
+
+
+
+ def initialize(self):
+ """ Opens the file, creates the pipe. """
+
+ cmd = [ FFMPEG_BINARY, '-i', self.filename,
+ '-f', 'image2pipe',
+ "-pix_fmt", self.pix_fmt,
+ '-vcodec', 'rawvideo', '-']
+ self.proc = sp.Popen( cmd, stdin=sp.PIPE,
+ stdout=sp.PIPE,
+ stderr=sp.PIPE)
+
+
+ def load_infos(self, print_infos=False):
+ """ reads the FFMPEG info on the file and sets self.size
+ and self.fps """
+ # open the file in a pipe, provoke an error, read output
+ proc = sp.Popen([FFMPEG_BINARY,"-i",self.filename, "-"],
+ stdin=sp.PIPE,
+ stdout=sp.PIPE,
+ stderr=sp.PIPE)
+ proc.stdout.readline()
+ proc.terminate()
+ infos = proc.stderr.read()
+ if print_infos:
+ # print the whole info text returned by FFMPEG
+ print infos
+
+ lines = infos.splitlines()
+ if "No such file or directory" in lines[-1]:
+ raise IOError("%s not found ! Wrong path ?"%self.filename)
+
+ # get the output line that speaks about video
+ line = [l for l in lines if ' Video: ' in l][0]
+
+ # get the size, of the form 460x320 (w x h)
+ match = re.search(" [0-9]*x[0-9]*(,| )",line)
+ self.size = map(int,line[match.start():match.end()-1].split('x'))
+
+ # get the frame rate
+ match = re.search("( [0-9]*.| )[0-9]* (tbr|fps)",line)
+ self.fps = float(line[match.start():match.end()].split(' ')[1])
+
+ # get duration (in seconds)
+ line = [l for l in lines if 'Duration: ' in l][0]
+ match = re.search(" [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9]",line)
+ hms = map(float,line[match.start()+1:match.end()].split(':'))
+ self.duration = cvsecs(*hms)
+ self.nframes = int(self.duration*self.fps)
+
+ def close(self):
+ self.proc.terminate()
+ for std in self.proc.stdin,self.proc.stdout,self.proc.stderr:
+ std.close()
+ del self.proc
+
+ def skip_frames(self,n=1):
+ """ Reads and throws away n frames """
+ w,h = self.size
+ for i in range(n):
+ self.proc.stdout.read(self.depth*w*h)
+ self.proc.stdout.flush()
+ self.pos += n
+
+
+ def read_frame(self):
+ w,h = self.size
+ try:
+ # Normally, the readr should not read after the last frame...
+ # if it does, raise an error.
+ s = self.proc.stdout.read(self.depth*w*h)
+ result = np.fromstring(s,
+ dtype='uint8').reshape((h,w,len(s)/(w*h)))
+ self.proc.stdout.flush()
+ except:
+ self.proc.terminate()
+ serr = self.proc.stderr.read()
+ print "error: string: %s, stderr: %s"%(s,serr)
+ raise
+
+ self.lastread = result
+
+ return result
+
+
+ def reinitialize(self,starttime=0):
+ """ Restarts the reading, starts at an arbitrary
+ location (!! SLOW !!) """
+ self.close()
+ if starttime==0:
+ self.initialize()
+ else:
+ offset = min(1,starttime)
+ cmd = [ FFMPEG_BINARY, '-ss',"%.03f"%(starttime- offset),
+ '-i', self.filename,
+ '-ss', "%.03f"%offset,
+ '-f', 'image2pipe',
+ "-pix_fmt", self.pix_fmt,
+ '-vcodec','rawvideo', '-']
+ self.proc = sp.Popen(cmd, stdin=sp.PIPE,
+ stdout=sp.PIPE,
+ stderr=sp.PIPE)
+
+ def get_frame(self,t):
+ """ Reads a frame at time t. Note for coders:
+ getting an arbitrary frame in the video with ffmpeg can be
+ painfully slow if some decoding has to be done. This
+ function tries to avoid fectching arbitrary frames whenever
+ possible, by moving between adjacent frames.
+ """
+ if t<0:
+ t=0
+ elif t>self.duration:
+ t = self.duration
+
+ pos = int(self.fps*t)+1
+ if pos == self.pos:
+ return self.lastread
+ else:
+ if (pos < self.pos) or (pos> self.pos+100):
+ self.reinitialize(t)
+ else:
+ self.skip_frames(pos-self.pos-1)
+ result = self.read_frame()
+ self.pos = pos
+ return result
+
+def read_image(filename,with_mask=True):
+ pix_fmt='rgba' if with_mask else "rgb24"
+ vf = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
+ vf.close()
+ return vf.lastread
diff --git a/moviepy/video/io/writers.py b/moviepy/video/io/writers.py
new file mode 100644
index 00000000..812d075f
--- /dev/null
+++ b/moviepy/video/io/writers.py
@@ -0,0 +1,137 @@
+"""
+On the long term this will implement several methods to make videos
+out of VideoClips
+"""
+
+import sys
+import numpy as np
+import subprocess as sp
+from moviepy.conf import FFMPEG_BINARY
+
+class FFMPEG_VideoWriter:
+ """ A class to read videos using ffmpeg. ffmpeg will read any kind
+ of videos and transform them into raw data (a long string that
+ can be reshaped into a RGB array).
+
+ :param filename: Any filename like 'video.mp4' etc. but if you
+ want to avoid complications it is recommended to use the
+ generic extension '.avi' for all your videos.
+ :param size: size (width,height) of the output video.
+ :param fps: frames per second of the output video.
+ :param codec: ffmpeg codec. It seems that in terms of quality
+ the hierarchy is
+
+ 'rawvideo' = 'png' > 'mpeg4' > 'libx264'
+
+ 'png' manages the same lossless quality as 'rawvideo' but
+ yields smaller files.
+
+ (type ffmpeg -codecs in a terminal)
+ :param bitrate: only relevant for codecs which accept a bitrate
+ bitrate = "5000k" offers nice results in general
+ :param withmask: True if there is a mask in the video to be
+ decoded.
+ """
+
+
+
+ def __init__(self, filename, size, fps, codec="libx264",
+ bitrate=None, withmask=False):
+
+ self.filename = filename
+ cmd = [ FFMPEG_BINARY, '-y',
+ "-f", 'rawvideo',
+ "-vcodec","rawvideo",
+ '-s', "%dx%d"%(size[0],size[1]),
+ '-pix_fmt', "rgba" if withmask else "rgb24",
+ '-r', "%.02f"%fps,
+ '-i', '-', '-an',
+ '-vcodec', codec] + (
+ ['-b',bitrate] if (bitrate!=None) else []) + [
+ '-r', "%d"%fps,
+ filename ]
+ self.proc = sp.Popen(cmd,stdin=sp.PIPE,
+ stdout=sp.PIPE,
+ stderr=sp.PIPE)
+
+ def write_frame(self,img_array):
+ self.proc.stdin.write(img_array.tostring())
+
+ def close(self):
+ self.proc.stdin.close()
+ del self.proc
+
+def ffmpeg_write(clip, filename, fps, codec="libx264", bitrate=None,
+ withmask=False, verbose=True):
+
+ if verbose:
+ def verbose_print(s):
+ sys.stdout.write(s)
+ sys.stdout.flush()
+ else:
+ verbose_print = lambda *a : None
+
+ verbose_print("Rendering video %s\n"%filename)
+ writer = FFMPEG_VideoWriter(filename, clip.size, fps, codec = codec,
+ bitrate=bitrate)
+ i=0
+ nframes = clip.duration*fps
+
+ while (i < nframes):
+ frame = clip.get_frame(1.0*i/fps)
+ if withmask:
+ mask = (255*clip.mask.get_frame(1.0*i/fps))
+ frame = np.dstack([frame,mask])
+
+ writer.write_frame(frame.astype("uint8"))
+ if ((i+1) % (nframes/10)) == 0:
+ verbose_print("=")
+ i += 1
+ writer.close()
+ verbose_print("video done !")
+
+
+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()
+
+
+# SAFETY WHEEL: opencv writer
+ #~
+#~ try:
+ #~ import cv2
+#~ except:
+ #~ print "OpenCV not found"
+#~ else:
+ #~ try:
+ #~ FOURCC = cv2.cv.FOURCC
+ #~ except:
+ #~ try:
+ #~ FOURCC = cv2.VideoWriter_fourcc
+ #~ except:
+ #~ print "Error : unable to find FOURCC in OpenCV."
+ #~ raise
+#~
+#~ def opencv_write(clip, filename, fps, codec, verbose=True):
+ #~
+ #~ if verbose:
+ #~ def verbose_print(s):
+ #~ sys.stdout.write(s)
+ #~ sys.stdout.flush()
+ #~ else:
+ #~ verbose_print = lambda *a : None
+ #~
+ #~ verbose_print("Rendering video %s\n"%filename)
+ #~ codec = 0 if (codec == 'raw') else FOURCC(*codec)
+ #~ writer = cv2.VideoWriter(filename, codec, fps, clip.size)
+ #~ i=0
+ #~ nframes = clip.duration*fps
+ #~ while (i < nframes):
+ #~ writer.write(clip.get_frame(1.0*i/fps)[:,:,::-1].astype('uint8'))
+ #~ if ((i+1) % (nframes/10)) == 0:
+ #~ verbose_print("=")
+ #~ i += 1
+ #~
+ #~ verbose_print("video done !")
diff --git a/moviepy/video/tools/__init__.py b/moviepy/video/tools/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/moviepy/video/tools/credits.py b/moviepy/video/tools/credits.py
new file mode 100644
index 00000000..3ef0c166
--- /dev/null
+++ b/moviepy/video/tools/credits.py
@@ -0,0 +1,91 @@
+"""
+This module contains different fonctions to make end and opening
+credits, even though it is difficult to fill everyone needs in this
+matter.
+"""
+
+from moviepy import TextClip, ImageClip, CompositeVideoClip
+from moviepy.video.fx import resize
+
+def credits1(creditfile,width,stretch=30,color='white',
+ stroke_color='black', stroke_width=2,
+ font='Impact-Normal',fontsize=60):
+ """
+
+ The first credits I imagined. They take as argument a file like: ::
+
+ # This is a comment
+ # The next line says : leave 4 blank lines
+ .blank 4
+
+ ..Executive Story Editor
+ MARCEL DURAND
+
+ ..Associate Producers
+ MARTIN MARCEL
+ DIDIER MARTIN
+
+ ..Music Supervisor
+ JEAN DIDIER
+
+ And produce an ImageClip that looks like :
+
+ Executive Story Editor MARCEL DURAND
+ Associate Producers MARTIN MARCEL
+ DIDIER MARTIN
+ Music Supervisor JEAN DIDIER
+
+ :param width: total width of the credits text
+ :param stretch: stretch in pixels between the jobs and the names.
+
+ The other keywords are passed to the ``TextClip``s
+ """
+
+
+ # PARSE THE TXT FILE
+
+ with open(creditfile) as f:
+ lines = f.readlines()
+
+ lines = filter(lambda x:not x.startswith('\n'),lines)
+ texts = []
+ oneline=True
+ for l in lines:
+ if not l.startswith('#'):
+ if l.startswith('.blank'):
+ for i in range(int(l.split(' ')[1])):
+ texts.append(['\n','\n'])
+ elif l.startswith('..'):
+ texts.append([l[2:],''])
+ oneline=True
+ else:
+ if oneline:
+ texts.append(['',l])
+ oneline=False
+ else:
+ texts.append(['\n',l])
+
+ left,right = [ "".join(l) for l in zip(*texts)]
+
+ # MAKE TWO COLUMNS FOR THE CREDITS
+
+ left,right = [TextClip(txt,color=color,stroke_color=stroke_color,
+ stroke_width=stroke_width,font=font,
+ fontsize=fontsize,align=al)
+ for txt,al in [(left,'East'),(right,'West')]]
+
+
+ cc = CompositeVideoClip( [left, right.set_pos((left.w+stretch,0))],
+ size = (left.w+right.w+stretch,right.h),
+ transparent=True)
+
+ # SCALE TO THE REQUIRED SIZE
+
+ scaled = cc.fx(resize , width=width)
+
+ # TRANSFORM THE WHOLE CREDIT CLIP INTO AN ImageCLip
+
+ imclip = ImageClip(scaled.get_frame(0))
+ amask = ImageClip(scaled.mask.get_frame(0),ismask=True)
+
+ return imclip.set_mask(amask)
diff --git a/moviepy/video/tools/drawing.py b/moviepy/video/tools/drawing.py
new file mode 100644
index 00000000..17c8e2e3
--- /dev/null
+++ b/moviepy/video/tools/drawing.py
@@ -0,0 +1,222 @@
+"""
+This module deals with making images (np arrays). It provides drawing
+methods that are difficult to do with the existing Python libraries.
+"""
+
+import numpy as np
+
+def blit(im1, im2, pos=[0, 0], mask=None, ismask=False):
+ """
+ Blits ``im1`` on ``im2`` as position ``pos=(x,y)``, using the
+ ``mask`` if provided. If ``im1`` and ``im2`` are mask pictures
+ (2D float arrays) then ``ismask`` must be ``True``.
+ """
+
+ # xp1,yp1,xp2,yp2 = blit area on im2
+ # x1,y1,x2,y2 = area of im1 to blit on im2
+ xp, yp = pos
+ x1 = max(0, -xp)
+ y1 = max(0, -yp)
+ h1, w1 = im1.shape[:2]
+ h2, w2 = im2.shape[:2]
+ xp2 = min(w2, xp + w1)
+ yp2 = min(h2, yp + h1)
+ x2 = min(w1, w2 - xp)
+ y2 = min(h1, h2 - yp)
+ xp1 = max(0, xp)
+ yp1 = max(0, yp)
+
+ if (xp1 >= xp2) or (yp1 >= yp2):
+ return im2
+
+ blitted = im1[y1:y2, x1:x2]
+
+ new_im2 = +im2
+
+ if mask != None:
+ mask = mask[y1:y2, x1:x2]
+ if len(im1.shape) == 3:
+ mask = np.dstack(3 * [mask])
+ blit_region = new_im2[yp1:yp2, xp1:xp2]
+ new_im2[yp1:yp2, xp1:xp2] = (
+ 1.0 * mask * blitted + (1.0 - mask) * blit_region)
+ else:
+ new_im2[yp1:yp2, xp1:xp2] = blitted
+
+ return new_im2.astype('uint8') if (not ismask) else new_im2
+
+
+
+def color_gradient(size,p1,p2=None,vector=None, r=None, col1=0,col2=1.0,
+ shape='linear', offset = 0):
+ """
+ Makes linear, bilinear, or radial gradients.
+
+ The result is a picture of size ``size``, whose color varies gradually: from
+ color `col1` in position ``p1`` to color ``col2`` in position ``p2``.
+
+ If it is a RGB picture the result must be transformed into
+ a 'uint8' array to be displayed normally:
+
+ >>> grad = colorGradient(blabla).astype('unit8')
+
+
+ :param size: size of the final picture/array
+
+ :param p1, p2: coordinates (x,y) of the border point for
+ ``col1`` and ``col2``
+
+ :param vector: can be provided instead of ``p2``. ``p2`` is then
+ defined as (p1 + vector).
+
+ :param col1, col2: can be floats to create gradient masks, or
+ [R,G,B] arrays to create gradient images.
+
+ :param shape: 'linear', 'bilinear', or 'circular'. In a linear gradient
+ the color varies in one direction, from point ``p1`` to point ``p2``.
+
+
+ :param offset: percentage of the vector at which the gradient actually
+ starts. for instance if offset is 0.9 in a gradient going from
+ p1 to p2, then the gradient will only occur near p2. If the offset
+ is 0.9 in a radial gradient, the gradient will occur in the region
+ located between 90% and 100% of the radius.
+
+ """
+
+ # np-arrayize and change x,y coordinates to y,x
+ w,h = size
+
+ col1, col2 = map(lambda x : np.array(x).astype(float), [col1, col2])
+
+ if shape == 'bilinear':
+ if vector is None:
+ vector = np.array(p2) - np.array(p1)
+ m1,m2 = [ colorGradient(size, p1, vector=v, col1 = 1.0, col2 = 0,
+ shape = 'linear', offset= offset)
+ for v in [vector,-vector]]
+
+ arr = np.maximum(m1,m2)
+ if col1.size > 1:
+ arr = np.dstack(3*[arr])
+ return arr*col1 + (1-arr)*col2
+
+
+ p1 = np.array(p1[::-1]).astype(float)
+
+ if vector is None:
+ if p2 != None:
+ p2 = np.array(p2[::-1])
+ vector = p2-p1
+ else:
+ vector = np.array(vector[::-1])
+ p2 = p1 + vector
+
+ if vector != None:
+ norm = np.linalg.norm(vector)
+
+ M = np.dstack(np.meshgrid(range(w),range(h))[::-1]).astype(float)
+
+ if shape == 'linear':
+
+ n_vec = vector/norm**2 # norm 1/norm(vector)
+
+ p1 = p1 + offset*vector
+ arr = (M- p1).dot(n_vec)/(1-offset)
+ arr = np.minimum(1,np.maximum(0,arr))
+ if col1.size > 1:
+ arr = np.dstack(3*[arr])
+ return arr*col1 + (1-arr)*col2
+
+ elif shape == 'radial':
+ if r is None:
+ r = norm
+ if r==0:
+ arr = np.ones((h,w))
+ else:
+ arr = (np.sqrt(((M- p1)**2).sum(axis=2)))-offset*r
+ arr = arr / ((1-offset)*r)
+ arr = np.minimum(1.0,np.maximum(0, arr) )
+
+ if col1.size > 1:
+ arr = np.dstack(3*[arr])
+ return (1-arr)*col1 + arr*col2
+
+
+def color_split(size,x=None,y=None,p1=None,p2=None,vector=None,
+ col1=0,col2=1.0, grad_width=0):
+ """
+ Makes an array of size ``size`` divided in two regions by a
+ straight line, the two regions having different colors.
+ provide either x, or y, or (c1,c2), or (c1,vector). See below.
+
+ Use:
+
+ >>> size = [200,200]
+ >>> # an image with all pixels with x<50 =0, the others =1
+ >>> colorSplit(size, x=50, col1=0, col2=1)
+ >>> # an image with all pixels with y<50 red, the others green
+ >>> colorSplit(size, x=50, col1=[255,0,0], col2=[0,255,0])
+ >>> # An image splitted along an arbitrary line (see below)
+ >>> colorSplit(size, p1=[20,50], p2=[25,70] col1=0, col2=1)
+
+
+ :param x (int): If provided, the image is splitted horizontally in x,
+ the left region being region 1.
+
+ :param y (int): If provided, the image is splitted vertically in y,
+ the top region being region 1.
+
+ :param p1,p2: Positions (x1,y1),(x2,y2), where the numbers can be floats,
+ of two points. Region 1 is defined as the region on the left when
+ going from p1 to p2.
+
+ :param p1, vector: p1 is (x1,y1) and vector (v1,v2), where the numbers
+ can be floats. Region 1 is then the region on the left when starting
+ in position p1 and going in the direction given by ``vector``.
+
+ :param gradient_width: if not null, the split is not sharp, but gradual
+ over a region of width ``gradient_width`` (in pixels). This is
+ preferable in many situations (for instance for antialiasing).
+
+ """
+
+ if grad_width or ( (x is None) and (y is None)):
+ if p2 != None:
+ vector = (np.array(p2) - np.array(p1))
+ x,y = vector
+ vector = np.array([y,-x]).astype('float')
+ norm = np.linalg.norm(vector)
+ vector = max(0.1,grad_width)*vector/norm
+ return color_gradient(size,p1,vector=vector,
+ col1 = col1, col2 = col2, shape='linear')
+ else:
+
+ w,h = size
+ shape = (h, w) if np.isscalar(col1) else (h, w, len(col1))
+ arr = np.zeros(shape)
+ print shape
+ if x != None:
+ arr[:,:x] = col1
+ arr[:,x:] = col2
+
+ elif y != None:
+ arr[:y] = col1
+ arr[y:] = col2
+
+ # if we are here, it means we didn't exit with a proper 'return'
+ print "Arguments in color_plit not understood !"
+ raise
+
+# to come: circles, squares, rectangles
+
+def circle(screensize, center, radius, col1=1.0, col2=0, blur=1):
+ """
+ Draws a circle of color ``col1``, on a background of color ``col2``,
+ on a screen of size ``screensize`` at the position ``center=(x,y)``,
+ with a radius ``radius`` but slightly blurred on the border by ``blur``
+ pixels
+ """
+ return color_gradient(screensize,p1=center,r=radius, col1=col1,
+ col2=col2, shape='radial', offset = 0 if (radius==0) else
+ 1.0*(radius-blur)/radius)
diff --git a/moviepy/video/tools/segmenting.py b/moviepy/video/tools/segmenting.py
new file mode 100644
index 00000000..43055dc9
--- /dev/null
+++ b/moviepy/video/tools/segmenting.py
@@ -0,0 +1,55 @@
+import numpy as np
+import scipy.ndimage as ndi
+from moviepy.video import ImageClip
+
+
+def findObjects(clip,rem_thr=500, preview=False):
+ """
+ Returns a list of ImageClips representing each a separate object on
+ the screen.
+
+ rem_thr : all objects found with size < rem_Thr will be
+ considered false positives and will be removed
+
+ """
+
+ image = clip.get_frame(0)
+ if clip.mask == None:
+ clip = clip.add_mask()
+
+ mask = clip.mask.get_frame(0)
+ labelled, num_features = ndi.measurements.label(image[:,:,0])
+
+ #find the objects
+ slices = ndi.find_objects(labelled)
+ # cool trick to remove letter holes (in o,e,a, etc.)
+ slices = [e for e in slices if mask[e[0],e[1]].mean() >0.2]
+ # remove very small slices
+ slices = [e for e in slices if image[e[0],e[1]].size > rem_thr]
+ # Sort the slices from left to right
+ islices = sorted(enumerate(slices), key = lambda s : s[1][1].start)
+
+ letters = []
+ for i,(ind,(sy,sx)) in enumerate(islices):
+ """ crop each letter separately """
+ sy = slice(sy.start-1,sy.stop+1)
+ sx = slice(sx.start-1,sx.stop+1)
+ letter = image[sy,sx]
+ labletter = labelled[sy,sx]
+ maskletter = (labletter==(ind+1))*mask[sy,sx]
+ letter = ImageClip(image[sy,sx])
+ letter.mask = ImageClip( maskletter,ismask=True)
+ letter.screenpos = np.array((sx.start,sy.start))
+ letters.append(letter)
+
+ if preview:
+ import matplotlib.pyplot as plt
+ print "found %d objects"%(num_features)
+ fig,ax = plt.subplots(2)
+ ax[0].axis('off')
+ ax[0].imshow(labelled)
+ ax[1].imshow([range(num_features)],interpolation='nearest')
+ ax[1].set_yticks([])
+ plt.show()
+
+ return letters
diff --git a/moviepy/video/tools/tracking.py b/moviepy/video/tools/tracking.py
new file mode 100644
index 00000000..e287fff3
--- /dev/null
+++ b/moviepy/video/tools/tracking.py
@@ -0,0 +1,180 @@
+"""
+This module contains different fonctions for tracking objects in videos,
+manually or automatically. The tracking functions return results under
+the form: ``( txy, (fx,fy) )`` where txy is of the form [(ti, xi, yi)...]
+and (fx(t),fy(t)) give the position of the track for all times t (if the
+time t is out of the time bounds of the tracking time interval
+fx and fy return the position of the object at the start or at the end
+of the tracking time interval).
+"""
+
+from scipy.interpolate import interp1d
+
+from moviepy.video.io.preview import imdisplay
+
+try:
+ import cv2
+except:
+ # Note: this will be later fixed with scipy/skimage replacements
+ # but for the moment OpenCV is mandatory, so...
+ print "WARNING: OpenCV not found: automated tracking not possible"
+
+
+
+# WE START WITH A TOOL FUNCTION
+
+def to_fxfy(txy_list, **kwargs):
+ """ Transforms a list [ (ti, (xi,yi)) ] into 2 functions (fx,fy)
+ where fx : t -> x(t) and fy : t -> y(t).
+ If the time t is out of the bounds of the tracking time interval
+ fx and fy return the position of the object at the start or at
+ the end of the tracking time interval.
+ Keywords can be passed to decide the kind of interpolation,
+ see the doc of ``scipy.interpolate.interp1d``."""
+
+ tt, xx, yy = zip(*txy_list)
+ interp_x = interp1d(tt, xx, **kwargs)
+ interp_y = interp1d(tt, yy, **kwargs)
+ fx = lambda t: xx[0] if (t <= tt[0]) else ( xx[-1] if t >= tt[-1]
+ else ( interp_x(t) ) )
+ fy = lambda t: yy[0] if (t <= tt[0]) else ( yy[-1] if t >= tt[-1]
+ else ( interp_y(t) ) )
+ return fx,fy
+
+
+# MANUAL TRACKING
+
+def manual_tracking(clip, t1=None, t2=None, fps=5, nobjects = 1):
+ """
+ Allows manual tracking of an object(s) in the video clip between
+ times `t1` and `t2`. This displays the clip frame by frame
+ and you must click on the object(s) in each frame. If ``t2=None``
+ only the frame at ``t1`` is taken into account.
+
+ Returns a list [(t1,x1,y1),(t2,x2,y2) etc... ] if there is one
+ object per frame, else returns a list whose elements are of the
+ form (ti, [(xi1,yi1), (xi2,yi2), ...] )
+
+ :param t1,t2: times during which to track (defaults are start and
+ end of the clip)
+ :param fps: Number of frames per second to freeze on.
+ :param nobjects: Number of objects to click on each frame
+
+
+
+ >>> print myClip.manTrack(10, 13,fps=7)
+ >>>
+ >>> # To print 5 points coordinates at t=5 :
+ >>> for i in range(5):
+ >>> print myClip.manTrack(5)
+
+ Tip: To avoid redoing the tracking each time you run your script,
+ better save the result the first time and then load it at each run.
+
+ >>> # First time:
+ >>> import pickle
+ >>> txy = myClip.manTrack(20, 10,fps=10)
+ >>> with open("chaplin_txy.dat",'w+') as f:
+ >>> pickle.dump(txy,f)
+ >>>
+ >>> # Next times:
+ >>> import pickle
+ >>> with open("chaplin_txy.dat",'r') as f:
+ >>> txy = pickle.load(txy,f)
+
+ """
+
+ import pygame as pg
+
+ screen = pg.display.set_mode(clip.size)
+ step = 1.0 / fps
+ if (t1 is None) and (t2 is None):
+ t1,t2 = 0, clip.duration
+ elif (t2 is None):
+ t2 = t1 + step / 2
+ t = t1
+ txy_list = []
+
+ def gatherClicks(t):
+
+ imdisplay(clip.get_frame(t), screen)
+ objects_to_click = nobjects
+ clicks = []
+ while objects_to_click:
+
+ for event in pg.event.get():
+
+ if event.type == pg.KEYDOWN:
+ if (event.key == pg.K_BACKSLASH):
+ return "return"
+
+
+ elif event.type == pg.MOUSEBUTTONDOWN:
+ x, y = pg.mouse.get_pos()
+ clicks.append((x, y))
+ objects_to_click -= 1
+
+ return clicks if (len(clicks)>1) else clicks[0]
+
+ while t < t2:
+
+ clicks =gatherClicks(t)
+ if clicks == 'return':
+ txy_list.pop()
+ t -= step
+ else:
+ txy_list.append((t,clicks))
+ t += step
+
+ return txy_list, to_fxfy(txy_list)
+
+
+
+
+
+
+# AUTOMATED TRACKING OF A PATTERN
+
+def findAround(pic,pat,xy=None,r=None):
+ """
+ find image pattern ``pat`` in ``pic[x +/- r, y +/- r]``.
+ if xy is none, consider the whole picture.
+ """
+
+ if xy and r:
+ h,w = pat.shape[:2]
+ x,y = xy
+ pic = pic[y-r : y+h+r , x-r : x+w+r]
+
+ matches = cv2.matchTemplate(pat,pic,cv2.TM_CCOEFF_NORMED)
+ yf,xf = np.unravel_index(matches.argmax(),matches.shape)
+ return (x-r+xf,y-r+yf) if (xy and r) else (xf,yf)
+
+
+def autoTrack(clip, pattern, tt=None, fps=None, radius=20, xy0=None):
+ """
+ Tracks a given pattern (small image array) in a video clip.
+ Returns [(x1,y1),(x2,y2)...] where xi,yi are
+ the coordinates of the pattern in the clip on frame i.
+ To select the frames you can either specify a list of times with ``tt``
+ or select a frame rate with ``fps``.
+ This algorithm assumes that the pattern's aspect does not vary much
+ and that the distance between two occurences of the pattern in
+ two consecutive frames is smaller than ``radius`` (if you set ``radius``
+ to -1 the pattern will be searched in the whole screen at each frame).
+ You can also provide the original position of the pattern with xy0.
+ """
+ if not xy0:
+ xy0 = findAround(clip.get_frame(tt[0]),pattern)
+
+ if tt is None:
+ tt = np.arange(0, clip.duration, 1.0/fps)
+
+ xys = [xy0]
+ for t in tt[1:]:
+ xys.append( findAround(clip.get_frame(t),pattern,
+ xy=xys[-1],r=radius))
+
+ xx,yy = zip(*xys)
+ txy_list = zip(tt,xx,yy)
+ return txy_list, to_fxfy(txy_list)
diff --git a/setup.py b/setup.py
index a58e6a30..d58e32b3 100644
--- a/setup.py
+++ b/setup.py
@@ -3,12 +3,11 @@
from setuptools import setup
setup(name='moviepy',
- version='0.1',
+ version='0.2',
author='Zulko 2013',
description='Module for script-based video editing',
long_description=open('README.rst').read(),
license='LICENSE.txt',
keywords="movie editing film mixing script-based",
packages=['moviepy'],
- install_requires = ['scipy','numpy','matplotlib','pygame',
- 'scikit-image','decorator', 'cython'])
+ install_requires = ['numpy','decorator','scipy','pygame'])