Video editing with Python
Rewrote a big share of the documentation for the new version of MoviePy (which doesn't require OpenCV)
Zulko43ec600b146e
diff --git a/README.rst b/README.rstindex 8657fef8..f30bcc6d 100644--- a/README.rst+++ b/README.rst@@ -13,17 +13,17 @@ A typical MoviePy script looks like that: ::from moviepy import *# Load myHolidays.mp4 and select the subclip 00:00:50 - 00:00:60- clip = MovieClip("myHolidays.mp4").subclip(50,60)+ clip =VideoFileClip("myHolidays.mp4").subclip(50,60)# Generate a text clip (many options available ! )txt_clip = TextClip("My Holidays 2013",fontsize=70,color='white')- txt_clip = txt_clip.set_pos(('center','center')).set_duration(10)+ txt_clip = txt_clip.set_pos('center').set_duration(10)# Overlay the text clip above the first clip- video = CompositeVideoClip(clip.size, [clip, txt_clip])+ final_clip = CompositeVideoClip([clip, txt_clip])# write the result to a file in any format- video.write("myHolidays_edited.avi",fps=25, codec='DIVX')+ final_clip.to_videofile("myHolidays_edited.avi",fps=25, codec='mpeg4')Download and Installationdiff --git a/docs/conf.py b/docs/conf.pyindex ec11bcb2..6762adc7 100644--- a/docs/conf.py+++ b/docs/conf.py@@ -25,7 +25,7 @@ import sys, os# Add any Sphinx extension module names here, as strings. They can be extensions# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.pngmath', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode']+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.viewcode']# Add any paths that contain templates here, relative to this directory.templates_path = ['_templates']@@ -48,9 +48,9 @@ copyright = u'2013, Zulko'# built documents.## The short X.Y version.-version = '0.1'+version = '0.2'# The full version, including alpha/beta/rc tags.-release = '0.1'+release = '0.2'# The language for content autogenerated by Sphinx. Refer to documentation# for a list of supported languages.diff --git a/docs/cookbook.rst b/docs/cookbook.rstdeleted file mode 100644index 53d896b4..00000000--- a/docs/cookbook.rst+++ /dev/null@@ -1,22 +0,0 @@-.. _cookbook:--Cookbook-========-The current policy of MoviePy is that most advanced features should not-be included in the core program, but should rather be provided by-individual coders as code snippets, by means of blogs, gits, etc.-Then one can make a customized ``moviepytools.py`` module containing-the advanced methods that one uses most.--In this cookbook you will find a few scripts for useful tasks-such as tracking an object, generating end credits, etc...-For more artistic and less general functionalities, see the :ref:`examples` .---.. toctree::- :maxdepth: 2-- cookbook/gradientEffect- cookbook/credits- cookbook/compoFromImage- cookbook/blurred_facediff --git a/docs/cookbook/blurred_face.rst b/docs/cookbook/blurred_face.rstdeleted file mode 100644index 5e6cf5e1..00000000--- a/docs/cookbook/blurred_face.rst+++ /dev/null@@ -1,134 +0,0 @@-========================================-Tracking and blurring someone's face-========================================----.. raw:: html-- <center>- <object><param name="movie"- value="http://www.youtube.com/v/FWCKYTRCrBI&hl=en_US&fs=1&rel=0">- </param><param name="allowFullScreen" value="true"></param><param- name="allowscriptaccess" value="always"></param><embed- src="http://www.youtube.com/v/FWCKYTRCrBI&hl=en_US&fs=1&rel=0"- type="application/x-shockwave-flash" allowscriptaccess="always"- allowfullscreen="true" width="550" height="450"></embed></object>- </center>--First we will need to track the face, i.e. to get two functions ``fx`` and ``fy`` such that ``(fx(t),fy(t))`` gives the position of the center of the head at time ``t``. This will be easily done with-:ref:`VideoClip.manual_tracking`. Then we will need to blur the area of the video around the center of the head.--To track an object in a video you write: ::-- txy = myClip.manual_tracking(0,5,fps=5)--This will display the frames of ``myClip`` between t=0s and t=5s and on each frame it will wait for you to click on the face. It then returns a list ``[(t1,x1,y1),(t2,x2,y2)]`` of the positions that you have clicked.--The next snippet uses these data to make the two functions ``(fx(t),fy(t))`` discussed above: ::-- from scipy.interpolate import interp1d-- def txy2functions(txyList):- """- Takes the output of VideoClip.manual_tracking and returns- 2 functions (fx,fy) where fx : t -> x(t) and fy : t -> y(t)- """- tt,xx,yy = zip(*txyList)- fx = interp1d(tt,xx,bounds_error=False, fill_value=xx[0])- fy = interp1d(tt,yy,bounds_error=False, fill_value=yy[0])- return fx,fy--And the coming function makes a filter that blurs the regions around ``(fx(t),fy(t))``: ::-- import cv2-- def blur_filter(fx,fy,r_zone,r_blur=None):- """- Returns a filter that will blurr a moving part 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.- """-- 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)- reg_res = y2-y1,x2-x1-- # We will now make a circled mask.- # IN older OpenCV, instead of the next two lines, write- # mask = cv2.circle(np.zeros(reg_res).astype('uint8'),- # (r_zone,r_zone),r_zone,255,-1, lineType=cv2.LINE_AA)- mask = np.zeros(reg_res).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 fl--Finally, here is the script: ::-- from moviepy import *- import pickle-- # Because we will work with sound and we do not want to carry around- # the sound of the whole original movie, we first extract the- # interesting part of the movie (run this line only once):-- ffmpeg.extract_subclip("./videos/chaplin.mp4",411.7,421.7+3,- "charlotSub.mp4")-- # Now we have a shorter movie that we can load- chaplin = MovieClip("charlotSub.mp4", audio=True)- clip = chaplin.subclip(0, chaplin.duration-3)--- # THE THREE NEXT LINES ARE FOR THE MANUAL TRACKING AND- # MUST BE COMMENTED ONCE THE TRACKING HAS BEEN DONE- # (AT FIRST RUN OF THE SCRIPT)- txyList = clip.manual_tracking(fps=6)- with open("chaplin_txy.dat",'w+') as f:- pickle.dump(txyList,f)-- # Load the tracking data (see comment above)- with open("chaplin_txy.dat",'r') as f:- fx,fy = txy2functions(pickle.load(f))--- # blur the head in the clip- clip_blurred = clip.fl(blur_filter(fx,fy,25))-- # Generate the text- txt = TextClip("Hey you ! \n You're blurry!", color='grey',- font = "Century-Schoolbook-Italic", fontsize=40)-- # Put the text on a grey background- txt = txt.on_color(chaplin.size,(25,25,25),("center","center"))-- # Concatenate the clip with the blur and the clip with text- # Set the audio of concat so that there will also be music- # when the text is playing.-- final = concat([clip_blurred,txt.set_duration(3)])- final = final.set_audio(chaplin.audio)-- # write to a file. Here we use the 'XVID' codec because- # 'raw' is too heavy and 'DIVX' is too ugly.-- final.to_movie('blurredChaplin.avi',fps=24, codec='XVID')-- # This 13s movie with sound and special effects was generated- # in six seconds.diff --git a/docs/cookbook/compoFromImage.rst b/docs/cookbook/compoFromImage.rstdeleted file mode 100644index 60d1b569..00000000--- a/docs/cookbook/compoFromImage.rst+++ /dev/null@@ -1,112 +0,0 @@-======================================-Placing clips according to a picture-======================================--So how do you do some complex compositing like this ?--.. raw:: html-- <center>- <object><param name="movie"- value="http://www.youtube.com/v/1hdgNxX-tas&hl=en_US&fs=1&rel=0">- </param><param name="allowFullScreen" value="true"></param><param- name="allowscriptaccess" value="always"></param><embed- src="http://www.youtube.com/v/1hdgNxX-tas&hl=en_US&fs=1&rel=0"- type="application/x-shockwave-flash" allowscriptaccess="always"- allowfullscreen="true" width="550" height="450"></embed></object>- </center>--It takes a lot of bad taste and... the right tools !--So we first make a picture that indicates the regions where the clips will be. This picture (that I made with Inkscape) is a *.png* that looks like this:--.. figure:: motif.jpeg--The next function finds the regions in the picture. For each region found it returns a mask that defines the region, and a tuple ``(x1,y1,x2,y2)`` defining a bounding rectangle giving the position of the region in the picture. ::-- import scipy.ndimage as spim- from pylab import *-- def pic2regions(pic,render=True, crop=True):- """- Finds the different regions contained in a delimited by- picture as a list of elements (maskClip,(x1,y1,x2,y2)).- maskClip is a clip ready to be used as a mask delimiting- the region. The resolution of maskClip is that of 'pic'- if crop=True, else, it is the size of the region.- render=True pops a picture rendering which region has- which number- """-- if len(pic.shape)>2:- pic = pic[:,:,0]- objects, num = spim.label(pic)- num = num+1- masks = [(objects==i).astype(float) for i in range(num)]- mamasks = [np.ma.masked_values(m,0) for m in masks]- h,w = pic.shape- XX,YY = [a for a in np.meshgrid(range(w),range(h))]- XXc = [ XX*c for c in mamasks]- YYc = [ YY*c for c in mamasks]- boxes = [ map(int,(xxc.min(),yyc.min(),xxc.max(),yyc.max()))- for xxc, yyc in zip(XXc, YYc)]-- if crop:- masks = [ m[y1:y2,x1:x2]- for m,(x1,y1,x2,y2) in zip (masks,boxes)]- print [m.shape for m in masks]-- maskClips = [ImageClip(m) for m in masks]-- if render:- print "found %d objects"%(num)- fig,ax = subplots(2)- ax[0].axis('off')- ax[0].imshow(objects)- ax[1].imshow([range(num)],interpolation='nearest')- ax[1].set_yticks([])-- return zip(maskClips,boxes)--This function returns a list of the regions found. To help visualize which element of the list corresponds to which region in the picture, ``pic2regions`` splashes a Matplotlib figure giving the index of each region. For our picture, it returned this: ::-- im = imread("./ultracompositing/motif.png")- regs = pic2regions(im)--.. figure:: matplotlibCompo.jpeg--Finally, we load 8 different video clips that we assign to the different regions. In our video, this implied for each of these clips--- Resizing the clip so that it will fill the region.-- Placing each clip at its position on the picture-- Giving to each clip a mask that will shape it like the region.--So here is the final script: ::-- # We load height clips from the US National Parks.- # These are public domain. :D- clips = [MovieClip(n).subclip(20,25) 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",- "./videos/grsm_0002.mov"]]-- im = imread("./ultracompositing/motif.png")- size = w,h = im.shape[:2][::-1]- regs = pic2regions(im,crop=True)- # eliminate the first region found (it is the border)- regs = regs[1:]- masks = [r[0] for r in regs]- poss = [(x1,y1) for m,(x1,y1,x2,y2) in regs]- comp_clips = [c.resize(m.size).set_mask(m).set_pos(p)- for c,m,p in zip(clips,masks,poss)]-- cc = CompositeVideoClip(size,comp_clips)- cc.resize(0.5).preview()--Nice and short ! And you can get very creative with this kind of tricks.-diff --git a/docs/cookbook/credits.rst b/docs/cookbook/credits.rstdeleted file mode 100644index c856773b..00000000--- a/docs/cookbook/credits.rst+++ /dev/null@@ -1,102 +0,0 @@-.. _autocredits:--==========================-Making Credits-==========================--Another advantage of scripting : we will see how to generate and animate some neat end credits. So here is a file ``EndCredits.txt``, which describes end credits in some weird yet understandable syntax (``.blank 4`` means "leave for blank lines"). ::-- .blank 4-- ..Executive Story Editor- MARCEL DURAND-- ..Associate Producers- MARTIN MARCEL- DIDIER MARTIN-- ..Music Supervisor- JEAN DIDIER-- ..First Assistant Director- THOMAS JEAN-- ..Second Assistant Director- MARIE THOMAS-- ..Guest Starring- EDMOND MARIE- MARIE JACQUES- JACQUES MARIVON- MARIVONNE ANDRE-- .blank 4--And here is a function that can parse this file to produce some neat credits: ::-- def make_credits(creditfile,width,stretch=30,color='white',- stroke_color='black', stroke_width=2,- font='Impact-Normal',fontsize=60):- """ Makes a nice credits picture from a text file"""--- # 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 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.w+right.w+stretch,right.h),- [left, right.set_pos((left.w+stretch,0))],- transparent=True)-- # SCALE TO THE REQUIRED SIZE-- scaled = cc.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)--Applied on the previous text file, this function returns something like this:--.. figure:: credits.jpeg--Now, you can make this picture move with something like ::-- CompositeVideoClip(myVideo.res,- [credits.set_pos(lambda t:('center',-speed*t))])--You can also do much more ! See for instance :ref:`mountainMask`.---diff --git a/docs/cookbook/gradientEffect.rst b/docs/cookbook/gradientEffect.rstdeleted file mode 100644index 522d8bdf..00000000--- a/docs/cookbook/gradientEffect.rst+++ /dev/null@@ -1,46 +0,0 @@-.. _gradients:--=================================-Gradient Effects-=================================--Gradients effects are extremely useful, for instance to make custom masks.-In most graphical softwares, if you point two positions ``x1`` and ``x2``-on the screen and choose two colors, you obtain a nice-color gradient like this:--.. figure:: gradient.jpeg--Here is an efficient implementation of the gradient ::-- def gradient(size,c1,c2,col1=0,col2=1.0):- """- size : size of the final picture- c1 : (x,y) of the border point of col1- c2 : (x,y) of the border point of col2- col1, col2: can be floats to create gradient masks, or- RGB arrays to create gradient images.- """-- c1, c2, col1, col2 = map(np.array,- [c1[::-1], c2[::-1], col1, col2])- vector = c2 - c1- norm = np.linalg.norm(vector)- n_vec = vector/norm**2- M = np.meshgrid(range(size[1]),range(size[0]))- arr = (dstack(M)-c1).dot(n_vec)- arr = np.minimum(1,np.maximum(0,arr))- return (col2*arr + col1- col1*arr).T--And while we are at it, here is the code for a bilateral gradient: ::-- def biGradient(size,c1,vector,col1=0,col2=1.0):- """ Returns a picture of size `res` where the pixel- at position `center` is of color `col1` and the color- is fading is fading to `col2` in the direction of- `vector` AND the opposite direction """- c1, vector = map(np.array,[c1,vector])- l1 = gradient(size,c1,c1+vector,col1,col2)- l2 = gradient(size,c1,c1-vector,col1,col2)- return np.minimum(l1,l2)-diff --git a/docs/cookbook/matplotlibCompo.jpeg b/docs/cookbook/matplotlibCompo.jpegdeleted file mode 100644index fdc8bd99..00000000Binary files a/docs/cookbook/matplotlibCompo.jpeg and /dev/null differdiff --git a/docs/crash_course/crash_course.rst b/docs/crash_course/crash_course.rstnew file mode 100644index 00000000..64fa6371--- /dev/null+++ b/docs/crash_course/crash_course.rst@@ -0,0 +1,247 @@+A MoviePy crash-course+-----------------------++In this section we will give you the basics to start editing your videos.++Example code+~~~~~~~~~~~~~~++In a typical script, you load or generate some clips, modify them, combine them, and write the result to a video file.+So let us load a movie of my last holidays, lower the volume, add a title in the center of the video for the ten first seconds, and write the result in a file: ::++ from moviepy import *++ # Load myHolidays.mp4 and select the subclip 00:00:50 - 00:00:60+ clip = VideoFileClip("myHolidays.mp4").subclip(50,60)++ # Reduce the audio volume (volume x 0.8)+ clip = clip.fx( afx.volumex, 0.8)++ # Generate a text clip. You can customize the font, color, etc.+ txt_clip = TextClip("My Holidays 2013",fontsize=70,color='white')++ # Say that you want it to appear 10s at the center of the screen+ txt_clip = txt_clip.set_pos('center').set_duration(10)++ # Overlay the text clip on the first video clip+ video = CompositeVideoClip([clip, txt_clip])++ # Write the result to a file+ video.to_videofile("myHolidays_edited.avi",fps=24, codec='mpeg4')++Classes of video clips+~~~~~~~~~~~~~~~~~~~~~~++Video clips are the building blocks of longer videos. They can be created with one of the following:++- ``VideoFileClip('myHolidays.mp4')`` for clips read from a movie file. See :class:`~moviepy.video.io.VideoFileClip.VideoFileClip`.+- ``ImageClip('myPic.png')`` for clips displaying a picture, for an *a priori* infinite duration. See :class:`~moviepy.video.ImageClip.ImageClip`.+- ``ColorClip((height,width),color=(R,G,B))`` for special ImageClips of a single color. See :class:`~moviepy.video.ImageClip.ColorClip`.+- ``TextClip('Hello folks !',font='Impact-Regular')`` for special ImageClips representing a text. They are automatically generated using ImageMagick. See :class:`~moviepy.video.ImageClip.TextClip`.++To that list we should add the ``CompositeVideoClips`` that are obtained by mixing several clips together.++.. _CompositeVideoClips:++Composite video clips+~~~~~~~~~~~~~~~~~~~~~++Composite video clips are video clips which will display the contents of several other video clips. The simplest compositing is concatenation with :meth:`~moviepy.video.compositing.concatenate.concatenate`: ::++ video = concatenate([clip1,clip2,clip3])++Now ``myVideo`` is a clip that plays the clips 1, 2, and 3 one after the other. You can also play a transition clip between the clips with the option ``transition=myClip``.++Next, you have the `~moviepy.video.compositing.CompositeVideoClip.CompositeVideoClip`: ::++ video = CompositeVideoClip(clip1.size, [clip1,clip2,clip3])++Now ``myVideo`` is a clip that has the size of ``clip1``, and plays ``clip1``, and ``clip2`` *on top of* ``clip1``, and ``clip3`` on top of+``clip1``, and ``clip2``. Of course, if ``clip2`` and ``clip3`` have the same size as ``clip1``, then only ``clip3``, which is on top, will be+visible in the video... unless ``clip3`` and ``clip2`` have masks which hide parts of them.++You can set the starting time of each clip as follows: ::++ video = CompositeVideoClip(clip.size, [clip1,clip2,clip3])++Because the three clips overlap, we can make them appear with a fading-in effect. Here we go for fadein effects that last 1.5 seconds: ::++ video = CompositeVideoClip([clip1, # starts at t=0+ clip2.set_start(50).fadein(1.5),+ clip3.set_start(90).fadein(1.5)])++Finally, if ``clip2`` and ``clip3`` are smaller than ``clip1``, you can decide where they will appear: ::++ video = CompositeVideoClip([clip1,+ clip2.set_pos((45,150)),+ clip3.set_pos((90,100))])++The size of the final clip is by default the size of the first clip in the list. If you want all your clips to appear in a composition of arbitrary size use argument ``size``: ::++ video = CompositeVideoClip([clip1.set_pos((45,150)),+ clip2.set_pos((45,150))],+ size = (720,460))++Note that there are many ways to specify the position: ::++ clip2.set_pos((45,150)) # x=45, y=150++ # clip2 is horizontally centered, and at the top of the picture+ clip2.set_pos(("center","top"))++ # clip2 is at 40% of the width, 70% of the height:+ clip2.set_pos((0.4,0.7), relative=True)++ # clip2's position is horizontally centered, and moving down !+ clip2.set_pos(lambda t: ('center', 50+t) )++Be careful when indicating the position that the ``y`` position has its zero at the top of the picture:++.. figure:: videoWH.jpeg++.. _renderingAClip:++Rendering a video clip+~~~~~~~~~~~~~~~~~~~~~~~++To preview one frame of the clip, use one of these: ::++ myClip.show() # shows the first frame of the clip+ myClip.show(10.5) # shows the frame of the clip at t=10.5s+ myClip.show(10.5,frontend="matplotlib") # show in a matplotlib window++To preview the clip, you type ::++ myClip.preview() # preview with default fps=15+ myClip.preview(fps=25)+ myClip.preview(fps=15, audio=False) # Play the clip with no sound.++Note that the ``fps`` can be any number, independently of the ``fps`` of your different sources.++To write a clip as a video file, use ::++ myClip.to_videofile("myEditedMovie.avi") # default: codec 'libx264' fps 24+ myClip.to_videofile("myEditedMovie.avi",fps=15, codec='mpeg4')+ myClip.to_videofile("myEditedMovie.avi",audio=False) # don't render the audio.+++Sometimes it is impossible for MoviePy to guess the ``duration`` attribute of the clip (keep in mind that some clips, like clips displaying a picture, have *a priori* an infinite duration). Then, the ``duration`` must be set manually with ``clip.set_duration``: ::++ myClip = Image("floawer.jpeg") # has infinite duration+ myClip.set_duration(5).preview() # will show flowers for 5 seconds++.. _CCaudioClips:++Audio clips+~~~~~~~~~~~~~++The second important objects of MoviePy are the audio clips. If ``myHolidays.mp4`` is a video with sound, then ::++ clip = VideoFileClip('myHolidays.mp4', audio=True)++will create a clip with a ``clip.audio`` attribute which is an audio clip. This is the sound that you will hear if you render the clip with ``clip.preview`` or ``clip.to_videofile``. You can also create an audio clip from a sound file and then attach it to a video clip: ::++ audio = AudioFileClip('mySong.wav')+ video = VideoFileClip('myHolidays.mp4').set_audio(audio)++Like video clips, audio clips can be cut (with ``clip.subclip``) modified (with for instance ``clip.volumex`` which multiplies the volume) and combined (with ``CompositeAudioClip``). But most of the time, MoviePy will do that for you:++- When you cut a video clip with ``videoclip.subclip(20,25)`` then the sound will also be cut, i.e. the resulting clip will have an audio clip ``videoclip.audio.subclip(20,25)``.+- When you put several clips together in a CompositeVideoClip, then the sound of the CompositeVideoClip will be the composition of the sounds of the different video clips.++For an example, you can refer to :ref:`soundexample`. Like video clips, sound clips have a ``get_frame`` attribute, and creating new audio clips by modifying or putting together other audio clips does not take place in the memory. The actual sounds of the audio clips are only computed when we ask to play them or to write them to a file. You can do that as follows: ::++ audioclip.preview() # default fps: 22050+ audioclip.preview(fps=44100)+ audioclip.to_soundfile('myclip.wav',fps=44100) #default fps: 22050++Operations on a clip+~~~~~~~~~~~~~~~~~~~~~++There are several categories of clip modifications in MoviePy.++The very common methods for composition (cutting a clip, setting its position, etc.) are implemented as ``clip.mymethod``. For instance ``clip.subclip(15,20)`` returns the part of ``clip`` that is playing between 15 seconds and 20 seconds.++For all the other modifications, we use ``clip.fx`` and ``clip.fl``. ``clip.fx`` is meant to make it easy to use already-written transformation functions, while ``clip.fl`` makes it easy to write new transformation functions.++Note that none of these methods occur *inplace*: they all create a copy of the clip and let the original clip untouched. Moreover, modified clips are just *special views* of the original clip, they do not carry all the video data with them. Actually, the *real* modifications are only performed when you are rendering the clip (see :ref:`renderingAClip`). This means that all the clip objects that you will create through modifications of other clips take virtually no place in the memory and are created quasi-instantly.++clip.fx+""""""""++Suppose that you have some functions implementing effects on clips: ::++ effect_1(clip, args1) -> new clip+ effect_2(clip, args2) -> new clip+ effect_3(clip, args3) -> new clip++where ``args`` represent arguments and/or keyword arguments. To apply these functions, in that order, to one clip, you would write something like ::++ newclip = effect_3( effect_2( effect_1(clip, args3), args2), args1)++but this is not easy to read. To have a clearer syntax you can use ``clip.fx``: ::++ newclip = clip.fx( effect_1, args1).\+ fx( effect_2, args2).\+ fx( effect_3, args3)++Much better ! There are already many effects implemented in the modules ``moviepy.video.fx`` and ``moviepy.audio.fx``. The fx methods in these modules are automatically applied to the sound and the mask of the clip if it is relevant, so that you don't have to worry about modifying these. For practicality, when you use ``from moviepy import *``, these two modules are loaded as ``vfx`` and ``afx``, so you may write something like ::++ from moviepy import *+ clip = VideoFileClip("myvideo.avi").\+ fx( vfx.resize, width=460).\ # resize (keep aspect ratio)+ fx( vfx.speedx, 2).\ # double speed+ fx( vfx.colorx, 0.5) # darken (decreases the RGB values)++++clip.fl+""""""""+++You can modify a clip as you want using custom *filters* with ``clip.fl_time``, ``clip.fl_image``, and more generally with ``clip.fl``.++You can change the timeline of the clip with ``clip.fl_time`` like this: ::++ modifiedClip1 = myClip.fl_time(lambda t: 3*t)+ modifiedClip2 = myClip.fl_time(lambda t: 1+sin(t))++Now the clip ``modifiedClip1`` plays the same as ``myClip``, only three times faster, while ``modifiedClip2`` will play ``myClip`` by oscillating between the times t=0s and t=2s. Note that in the last case you have created a clip of infinite duration (which is not a problem for the moment).++You can also modify the display of a clip with ``clip.fl_image``. The following takes a clip and inverts the green and blue channels: ::++ modifiedClip = myClip.fl_image(lambda image: image[:,:,[0,2,1]])++Finally, you may want to process the clip by taking into account the time and the picture at the same time. This is possible with ``clip.fl``. The filter must be a function which takes two arguments and returns a picture. the fist argument is a ``get_frame`` method (i.e. a function ``g(t)`` which given a time returns the clip's frame at that time), and the second argument is the time. ::++ modifiedClip = myClip.fl(lambda gf,t: gf(t)[int(t):int(t)+360,:]++This will scroll down the clip with a constant height of 360 pixels.++Prefer using ``fl_time`` and ``fl_image`` if possible when implementing new effects. The reason is that for image clips MoviePy will recognize that these methods do not need to be applied to each frames, which will result in shorter computation times.++Tools+~~~~~~++Advanced features of MoviePy that cannot be expressed as an ``fx`` are placed in :module:`moviepy.video.tools` (currently this module contains methods for tracking objects, segmenting, drawing, making credits) and `moviepy.audio.tools` (currently empty, will contain denoisers and utilities for synchronization).++Tips+~~~~~++MoviePy works fine on my 1.5 petaflops supercomputer but when a clip gets very complex the rendering is slow and there is not much we can do.++- Use an interactive shell, like IPython or, better, the IPython notebook. If you don't know these, you don't know what you are missing !+- If a part of your video takes a lot of time to render, save it once and for all as a video, then use this video. Choose codec 'rawvideo' or 'png' for lossless saving.+- Prefer the ``clip.show()`` option, and use it a lot. Only use ``clip.preview()`` when really necessary.+- If the previewing is shaky, it means that your computer is not good enough to render the clip in real time. Don't hesitate to play with the options of ``preview``: for instance, lower the fps of the sound (11000 Hz is still fine) and the video.+- Prototype: design your clips separately. If your composition involves a clip that is not finished yet, replace it temporarily with a basic color clip.+- There are often several ways to produce a same effect with MoviePy, but some ways are faster. For instance don't apply effects to a whole screen video if you are only using one region of the screen afterwards: first crop the selected region, then apply your effects.+- [wishful thinking] Check on the internet or in the examples of this documentation that what you do hasn't been done before. Code shared on the internet has more chances to be optimized.+++To go further and learn about all the available options and functionalities of MoviePy, see the :ref:`examples` and the reference manual. You can also browse the code of different fx+++++diff --git a/docs/first_steps/videoWH.jpeg b/docs/crash_course/videoWH.jpegsimilarity index 100%rename from docs/first_steps/videoWH.jpegrename to docs/crash_course/videoWH.jpegdiff --git a/docs/examples.rst b/docs/examples.rstdeleted file mode 100644index 7c68931d..00000000--- a/docs/examples.rst+++ /dev/null@@ -1,24 +0,0 @@-.. _examples:--Example Scripts-===============--Here are a few example scripts to get you started, including, as promised,-the scripts used for all the clips of the demonstration video. This section-may soon be replaced by a list of links to internet resources.---.. toctree::- :maxdepth: 1-- examples/textmovingletters- examples/musicVideo- examples/soundExample- examples/starwarslike- examples/mountainMask- examples/the_end- examples/freezepainting- examples/logo---diff --git a/docs/cookbook/motif.jpeg b/docs/examples/compo_from_image.jpegsimilarity index 100%rename from docs/cookbook/motif.jpegrename to docs/examples/compo_from_image.jpegdiff --git a/docs/examples/compo_from_image.rst b/docs/examples/compo_from_image.rstnew file mode 100644index 00000000..8d3cd24c--- /dev/null+++ b/docs/examples/compo_from_image.rst@@ -0,0 +1,33 @@+======================================+Placing clips according to a picture+======================================+++So how do you do some complex compositing like this ?++.. raw:: html++ <center>+ <object><param name="movie"+ value="http://www.youtube.com/v/1hdgNxX-tas&hl=en_US&fs=1&rel=0">+ </param><param name="allowFullScreen" value="true"></param><param+ name="allowscriptaccess" value="always"></param><embed+ src="http://www.youtube.com/v/1hdgNxX-tas&hl=en_US&fs=1&rel=0"+ type="application/x-shockwave-flash" allowscriptaccess="always"+ allowfullscreen="true" width="550" height="450"></embed></object>+ </center>++It takes a lot of bad taste, and a segmenting tool++In this script we will use this image (generated with Inkscape):++.. figure:: compo_from_image.jpeg++We will find the regions of this image and fit the different clips into these regions:++.. literalinclude:: ../../examples/compo_from_image.py+++(note that some pictures are distorted here as their size has been modified without care for their aspect ratio. This could be changed with a few more lines.)++diff --git a/docs/examples/example_with_sound.rst b/docs/examples/example_with_sound.rstnew file mode 100644index 00000000..fe0a2a1f--- /dev/null+++ b/docs/examples/example_with_sound.rst@@ -0,0 +1,22 @@+.. soundexample:++An example with sound+------------------------++An example of using MoviePy to assemble movie clips with sounds. Here are two scenes of Charade put together:++.. raw:: html++ <center>+ <object><param name="movie"+ value="http://www.youtube.com/v/gtyFuIoH7W0&hl=en_US&fs=1&rel=0">+ </param><param name="allowFullScreen" value="true"></param><param+ name="allowscriptaccess" value="always"></param><embed+ src="http://www.youtube.com/v/gtyFuIoH7W0&hl=en_US&fs=1&rel=0"+ type="application/x-shockwave-flash" allowscriptaccess="always"+ allowfullscreen="true" width="550" height="450"></embed></object>+ </center>++Here is the code:++.. literalinclude:: ../../examples/example_with_sound.pydiff --git a/docs/examples/examples.rst b/docs/examples/examples.rstnew file mode 100644index 00000000..7539ce03--- /dev/null+++ b/docs/examples/examples.rst@@ -0,0 +1,25 @@+.. _examples:++Example Scripts+===============++Here are a few example scripts to get you started, including, as promised,+the scripts used for the clips of the demonstration video.+++.. toctree::+ :maxdepth: 1++ moving_letters+ ukulele_concerto+ example_with_sound+ star_worms+ masked_credits+ painting_effect+ compo_from_image+ headblur+ the_end++++diff --git a/docs/examples/freezepainting.rst b/docs/examples/freezepainting.rstdeleted file mode 100644index b5eb5651..00000000--- a/docs/examples/freezepainting.rst+++ /dev/null@@ -1,86 +0,0 @@-=============================================-Freezing a movie frame with a painting effect-=============================================--That's an effect that we have seen a lot in westerns and such.--.. raw:: html-- <center>- <object><param name="movie"- value="http://www.youtube.com/v/aC5CifkacSI&hl=en_US&fs=1&rel=0">- </param><param name="allowFullScreen" value="true"></param><param- name="allowscriptaccess" value="always"></param><embed- src="http://www.youtube.com/v/aC5CifkacSI&hl=en_US&fs=1&rel=0"- type="application/x-shockwave-flash" allowscriptaccess="always"- allowfullscreen="true" width="550" height="450"></embed></object>- </center>--Before-starting let us see how to make a photo look more like a painting. It-can be done easy as follows:--- Find the edges of the image with the Sobel algorithm. What you obtain- is what looks like a hand-drawing of the photo.-- Multiply the image to make the colors flashier, and add the contours- obtained at the previous step.--Which is implemented in just a few lines of code: ::-- from moviepy import *- from skimage.filter import sobel-- 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')--Now let us see the actual script. We work on an Audrey Hepburn clip taken-from *Charade*, a movie which is not copyrighted due to a copyright-omission (good for us).--The final clip will be the concatenation of three part: the part before-the effect, the part with the effect, and the part after the effect.-The part with the effect is obtained as follows:--- Take the frame to freeze and make a "painted image" of it. Make it a clip.-- Add a text clip saying "Audrey" to the "painted image" clip.-- Overlay the painted clip over the original frame, but make it appear and- disappear with a fading effect.--Here you are for the code: ::-- charade = MovieClip("./videos/charade.mp4", audio=False)- tf = 19*60+21.0 # Time of the freeze, 19'21-- # WE TAKE THE SUBCLIPS WHICH ARE 2 SECONDS BEFORE & AFTER THE FREEZE-- clip_before = charade.subclip(tf -2,tf )- clip_after = charade.subclip(tf ,tf +2)--- # THE FRAME TO FREEZE-- im_freeze = charade.get_frame(tf)- painting = ImageClip(to_painting(im_freeze))- txt = TextClip('Audrey',font='Amiri-regular',fontsize=35)- painting_txt = CompositeVideoClip(charade.size,- [painting,txt.set_pos((10,180))])-- # FADEIN/FADEOUT EFFECT ON THE PAINTED IMAGE-- painting_fading = CompositeVideoClip(charade.size,- [ImageClip(im_freeze),- painting_txt.with_mask().fadein(0.3).- set_duration(3).- fadeout(0.3)])-- # FINAL CLIP AND RENDERING-- final_clip = concat([ clip_before,- painting_fading.set_duration(3.6),- clip_after])-- final_clip.to_movie('audrey.avi',fps=charade.fps)diff --git a/docs/examples/headblur.rst b/docs/examples/headblur.rstnew file mode 100644index 00000000..5c428552--- /dev/null+++ b/docs/examples/headblur.rst@@ -0,0 +1,20 @@+========================================+Tracking and blurring someone's face+========================================++.. raw:: html++ <center>+ <object><param name="movie"+ value="http://www.youtube.com/v/FWCKYTRCrBI&hl=en_US&fs=1&rel=0">+ </param><param name="allowFullScreen" value="true"></param><param+ name="allowscriptaccess" value="always"></param><embed+ src="http://www.youtube.com/v/FWCKYTRCrBI&hl=en_US&fs=1&rel=0"+ type="application/x-shockwave-flash" allowscriptaccess="always"+ allowfullscreen="true" width="550" height="450"></embed></object>+ </center>++First we will need to track the face, i.e. to get two functions ``fx`` and ``fy`` such that ``(fx(t),fy(t))`` gives the position of the center of the head at time ``t``. This will be easily done with+`manual_tracking`. Then we will need to blur the area of the video around the center of the head.++.. literalinclude:: ../../examples/headblur.pydiff --git a/docs/examples/logo.rst b/docs/examples/logo.rstindex 1233c38b..270cdc9c 100644--- a/docs/examples/logo.rst+++ b/docs/examples/logo.rst@@ -30,4 +30,4 @@ Here the logo is a picture, while the shadow is actually a black rectangle takinshade.mask.get_frame = lambda t : f(t,moviesize,duration)cc = CompositeVideoClip(moviesize,[im.set_pos(2*["center"]),shade])- cc.subclip(0,duration).to_movie("moviepy_logo.avi",fps=24)+ cc.subclip(0,duration).to_videofile("moviepy_logo.avi",fps=24)diff --git a/docs/examples/mountainMask.rst b/docs/examples/masked_credits.rstsimilarity index 56%rename from docs/examples/mountainMask.rstrename to docs/examples/masked_credits.rstindex 3445d20d..d2649c59 100644--- a/docs/examples/mountainMask.rst+++ b/docs/examples/masked_credits.rst@@ -33,28 +33,6 @@ First, see in :ref:`autocredits` how to make credits automatically with MoviePy.-And here is the code: ::-- from moviepy import *-- # Load the mountains clip, cut it, slow it down, make it look darker- clip = MovieClip('./mountain.mov',audio=False).subclip(37,46).speedx(0.4)- clip = clip.fl_image(lambda pic: (0.7*pic).astype('uint8'))-- # Save the first frame to later make a mask with GIMP (only once)- # clip.save_frame('mountain.png')-- # Load the mountain mask made with GIMP- mountainmask = ImageClip('./credits/mountainMask2.png',ismask=True)-- # Generate the credits from a text file- credits = make_credits('./credits/credits.txt',3*clip.w/4)-- # Make the credits scroll. Here, 10 pixels per second- mov_credits= CompositeVideoClip(clip.size,[- clip,- credits.set_pos(lambda t:('center',-10*t)),- clip.set_mask(mountainmask)])-- final = CompositeVideoClip(clip.size,[clip,mov_credits.set_end(25)])- final.subclip(8,15).to_movie("credits_mount.avi",fps=24,codec='DIVX')+And here is the code:++.. literalinclude:: ../../examples/masked_credits.pydiff --git a/docs/examples/moving_letters.rst b/docs/examples/moving_letters.rstnew file mode 100644index 00000000..0b4f910f--- /dev/null+++ b/docs/examples/moving_letters.rst@@ -0,0 +1,22 @@+=============================+Text with moving letters+=============================++I think this example illustrates well the interest of script-based editing (imagine doing that by hand).++.. raw:: html++ <center>+ <object><param name="movie"+ value="http://www.youtube.com/v/jj5qrHl5ZS0&hl=en_US&fs=1&rel=0">+ </param><param name="allowFullScreen" value="true"></param><param+ name="allowscriptaccess" value="always"></param><embed+ src="http://www.youtube.com/v/jj5qrHl5ZS0&hl=en_US&fs=1&rel=0"+ type="application/x-shockwave-flash" allowscriptaccess="always"+ allowfullscreen="true" width="550" height="450"></embed></object>+ </center>+++Here is the code:++.. literalinclude:: ../../examples/moving_letters.pydiff --git a/docs/examples/musicVideo.rst b/docs/examples/musicVideo.rstdeleted file mode 100644index 1c37e968..00000000--- a/docs/examples/musicVideo.rst+++ /dev/null@@ -1,61 +0,0 @@-======================-A simple music video-======================--.. raw:: html-- <center>- <object><param name="movie"- value="http://www.youtube.com/v/AqGZ4JFkQTU&hl=en_US&fs=1&rel=0">- </param><param name="allowFullScreen" value="true"></param><param- name="allowscriptaccess" value="always"></param><embed- src="http://www.youtube.com/v/AqGZ4JFkQTU&hl=en_US&fs=1&rel=0"- type="application/x-shockwave-flash" allowscriptaccess="always"- allowfullscreen="true" width="550" height="450"></embed></object>- </center>---This is an example, with no sound (lame for a music video), soon to be-replaced with a real music video example (the code will be 99% the same).-The philosophy of MoviePy is that for each new music video I will make,-I will just have to copy/paste this code, and modify a few lines. ::-- from moviepy import *--- # UKULELE CLIP, OBTAINED BY CUTTING AND CROPPING- # RAW FOOTAGE-- ukulele = (MovieClip("./videos/moi_ukulele.MOV",audio=False).- subclip(60+33,60+50).- crop(486,180,1196,570))-- w,h = moviesize = ukulele.size-- # THE PIANO FOOTAGE IS DOWNSIZED, HAS A WHITE MARGIN, IS- # IN THE BOTTOM LEFT CORNER-- piano = (MovieClip("./videos/douceamb.mp4",audio=False).- subclip(30,50).- resize((w/3,h/3)).- margin(6,color=(255,255,255)). #white margin- 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",- color='white',fontsize=24)- txt_col = txt.on_color(size=(ukulele.w + txt.w,txt.h+6), 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(moviesize,[ukulele,txt_mov,piano])- final.subclip(0,5).to_movie("ukulele.avi",fps=24,codec='DIVX')diff --git a/docs/examples/painting_effect.rst b/docs/examples/painting_effect.rstnew file mode 100644index 00000000..a27737a2--- /dev/null+++ b/docs/examples/painting_effect.rst@@ -0,0 +1,38 @@+=============================================+Freezing a movie frame with a painting effect+=============================================++That's an effect that we have seen a lot in westerns and such.++.. raw:: html++ <center>+ <object><param name="movie"+ value="http://www.youtube.com/v/aC5CifkacSI&hl=en_US&fs=1&rel=0">+ </param><param name="allowFullScreen" value="true"></param><param+ name="allowscriptaccess" value="always"></param><embed+ src="http://www.youtube.com/v/aC5CifkacSI&hl=en_US&fs=1&rel=0"+ type="application/x-shockwave-flash" allowscriptaccess="always"+ allowfullscreen="true" width="550" height="450"></embed></object>+ </center>++The recipe used to make a photo look like a painting:++- Find the edges of the image with the Sobel algorithm. You obtain+ what looks like a black and white hand-drawing of the photo.+- Multiply the image array to make the colors flashier, and add the contours+ obtained at the previous step.++The final clip will be the concatenation of three part: the part before+the effect, the part with the effect, and the part after the effect.+The part with the effect is obtained as follows:++- Take the frame to freeze and make a "painted image" of it. Make it a clip.+- Add a text clip saying "Audrey" to the "painted image" clip.+- Overlay the painted clip over the original frame, but make it appear and+ disappear with a fading effect.++Here you are for the code:++.. literalinclude:: ../../examples/painting_effect.py+diff --git a/docs/examples/soundExample.rst b/docs/examples/soundExample.rstdeleted file mode 100644index cea3cc47..00000000--- a/docs/examples/soundExample.rst+++ /dev/null@@ -1,86 +0,0 @@-.. soundexample:--An example with sound---------------------------An example of using MoviePy to assemble movie clips with sounds. Here are two scenes of Charade put together:--.. raw:: html-- <center>- <object><param name="movie"- value="http://www.youtube.com/v/gtyFuIoH7W0&hl=en_US&fs=1&rel=0">- </param><param name="allowFullScreen" value="true"></param><param- name="allowscriptaccess" value="always"></param><embed- src="http://www.youtube.com/v/gtyFuIoH7W0&hl=en_US&fs=1&rel=0"- type="application/x-shockwave-flash" allowscriptaccess="always"- allowfullscreen="true" width="550" height="450"></embed></object>- </center>--Here is the code: ::-- from moviepy import *- import numpy as np-- # LOAD MOVIE-- charade = MovieClip("./charadePhone.mp4",audio=True)- w,h = charade.size- duration=6---- # MAKE THE LEFT CLIP-- # cut and crop the clip- xleft = 60- clip_left = charade.subclip(0,duration)- clip_left = clip_left.crop(x1=xleft,x2=xleft+2*w/3)-- # make the mask. Yeah it's complicated, there must be a simpler way.- # It is just a mask that is black on the right bottom corner.- c1a = np.array((2*w/3,0))- v1 = np.array([h,w/3])- v1 = 2*v1/np.linalg.norm(v1)- c1b = c1a- v1- g1 = gradient(clip_left.size,c1a,c1b,col1=0,col2=1.0)- clip_left.mask = ImageClip(g1,ismask=True)---- # MAKE THE RIGHT CLIP-- # cut and crop the clip- xright = 70- clip_right = charade.subclip(21,21+duration)- clip_right = clip_right.crop(x1=xright,x2=xright+2*w/3)-- # make the mask- c2a = np.array((w/3,0))- c2b = c2a+v1- g2 = gradient(clip_right.size,c2a,c2b,col1=0,col2=1.0)- clip_right.mask = ImageClip(g2,ismask=True)--- # ASSEMBLE AND WRITE THE MOVIE-- cc = CompositeVideoClip(charade.size,- [clip_right.set_pos(('right',0)),- clip_left.set_pos(('left',0))])-- cc.to_movie("biphone.avi")---A few remarks:--- In this script we never explicitly consider the sound. MoviePy does all the cutting and the mixing automatically.-- We do not load the whole movie but just a part of it (never load a 2h00 movie when you are going to use its sound, see the remark in :ref:`goodPractices`). Rather, we first extract the part of interest with ::-- import moviepy.ffmpeg as ff- t1 = 3050 #seconds- t2 = 3095- ff.extract_subclip("charade.mp4",t1,t2,"charadePhone.mp4")--- We use a nerdy and complicated way of cutting the clips with the ``gradient`` function (defined in :ref:`gradients`) but you could have done it with masks from images for instance.--diff --git a/docs/examples/star_worms.rst b/docs/examples/star_worms.rstnew file mode 100644index 00000000..d61754c1--- /dev/null+++ b/docs/examples/star_worms.rst@@ -0,0 +1,34 @@+A Star-Wars like opening title+-------------------------------++This is an approximate effect (the perspective would require some more complex transformations) but it is a nice exercice. Achtung: clip with sound.++.. raw:: html++ <center>+ <object><param name="movie"+ value="http://www.youtube.com/v/5euLdo8L0o0&hl=en_US&fs=1&rel=0">+ </param><param name="allowFullScreen" value="true"></param><param+ name="allowscriptaccess" value="always"></param><embed+ src="http://www.youtube.com/v/5euLdo8L0o0&hl=en_US&fs=1&rel=0"+ type="application/x-shockwave-flash" allowscriptaccess="always"+ allowfullscreen="true" width="550" height="450"></embed></object>+ </center>++Let us also have a look at this tutorial which shows the different steps:++.. raw:: html++ <center>+ <object><param name="movie"+ value="http://www.youtube.com/v/dGrP7GhzWEE&hl=en_US&fs=1&rel=0">+ </param><param name="allowFullScreen" value="true"></param><param+ name="allowscriptaccess" value="always"></param><embed+ src="http://www.youtube.com/v/dGrP7GhzWEE&hl=en_US&fs=1&rel=0"+ type="application/x-shockwave-flash" allowscriptaccess="always"+ allowfullscreen="true" width="550" height="450"></embed></object>+ </center>++And here you are for the code, and for the code of the tutorial.++.. literalinclude:: ../../examples/star_worms.pydiff --git a/docs/examples/starwarslike.rst b/docs/examples/starwarslike.rstdeleted file mode 100644index 3c0b5d70..00000000--- a/docs/examples/starwarslike.rst+++ /dev/null@@ -1,192 +0,0 @@-A Star-Wars like opening title----------------------------------This is an approximate effect (the perspective would require some more complex transformations) but it is a nice exercice. Achtung: clip with sound.--.. raw:: html-- <center>- <object><param name="movie"- value="http://www.youtube.com/v/5euLdo8L0o0&hl=en_US&fs=1&rel=0">- </param><param name="allowFullScreen" value="true"></param><param- name="allowscriptaccess" value="always"></param><embed- src="http://www.youtube.com/v/5euLdo8L0o0&hl=en_US&fs=1&rel=0"- type="application/x-shockwave-flash" allowscriptaccess="always"- allowfullscreen="true" width="550" height="450"></embed></object>- </center>--Before seeing the code, let us have a look at this tutorial which shows the different steps:--.. raw:: html-- <center>- <object><param name="movie"- value="http://www.youtube.com/v/dGrP7GhzWEE&hl=en_US&fs=1&rel=0">- </param><param name="allowFullScreen" value="true"></param><param- name="allowscriptaccess" value="always"></param><embed- src="http://www.youtube.com/v/dGrP7GhzWEE&hl=en_US&fs=1&rel=0"- type="application/x-shockwave-flash" allowscriptaccess="always"- allowfullscreen="true" width="550" height="450"></embed></object>- </center>--And here you are for the code (it uses the ``gradient`` function, see :ref:`gradients`): ::-- from moviepy import *- from skimage import transform as tf-- def trapzWarp(pic,cx,cy,ismask=False):- """" Warps the given picture into a trapezoid.- Warning: slow function. """- 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')-- # RESOLUTION 16 / 9- w = 720- h = w*9/16- 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',remove_temp=False)---- # 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 VANISHING EFFECT ON THE TEXT-- grad = gradient(moving_txt.size,c1=(0,2*h/3),- c2=(0,h/4),col1=1.0,col2=0.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 (PERSPECTIVE EFFECT)-- 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--- txt_duration = 2*clip_txt.size[1]/txt_speed- movie_duration = txt_duration+5-- cc = CompositeVideoClip(moviesize,[- stars.set_duration(movie_duration),- warped_txt.set_duration(txt_duration)- .set_pos(('center','bottom'))])--- cc.subclip(0,3).preview()---Code for the tutorial-~~~~~~~~~~~~~~~~~~~~~~--Here is the code I used to make the tutorial. 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). Once again, scripting is very useful to make such videos. ::-- 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)-- cvc = CompositeVideoClip(clip.size,- [clip , txtclip.on_color((clip.w,txtclip.h+6),- color=(0,0,255),pos=(6,'center')).- set_pos((0,'bottom'))])-- return cvc.set_duration(clip.duration)-- # A few functions to resize/center clips that have different sizes.-- def resizeCenter(clip):- return clip.resize(height=h).set_pos(('center','center'))-- def composeCenter(clip):- return CompositeVideoClip(moviesize,- [clip.set_pos(('center','center'))])-- # Annotations-- annotations = [-- annotate(composeCenter(resizeCenter(stars)).subclip(0,3),- "This is a public domain picture of stars"),-- annotate(CompositeVideoClip(moviesize,[stars]).subclip(0,3),- "We only keep one part."),-- annotate(CompositeVideoClip(moviesize,[stars_darkened]).subclip(0,3),- "We darken it a little."),-- annotate(composeCenter(resizeCenter(clip_txt)).subclip(0,3),- "We generate a text image."),-- annotate(composeCenter(moving_txt.set_mask(None)).subclip(6,9),- "We scroll the text by cropping a moving region of it."),-- annotate(composeCenter(gradmask.toRGB()).subclip(0,2),- "We add this mask to the clip."),-- annotate(composeCenter(moving_txt).subclip(6,9),- "Here is the result"),-- annotate(composeCenter(warped_txt).subclip(6,9),- "We now warp this clip in a trapezoid."),-- annotate(cc.subclip(6,9),- "We finally superimpose with the stars.")- ]-- annotations_video = concat(annotations)- annotations_video.to_movie('tutorial.avi')diff --git a/docs/examples/textmovingletters.rst b/docs/examples/textmovingletters.rstdeleted file mode 100644index 1544986d..00000000--- a/docs/examples/textmovingletters.rst+++ /dev/null@@ -1,134 +0,0 @@-=============================-Text with moving letters-=============================--I think this example illustrates well the interest of script-based editing (imagine doing that by hand).--.. raw:: html-- <center>- <object><param name="movie"- value="http://www.youtube.com/v/jj5qrHl5ZS0&hl=en_US&fs=1&rel=0">- </param><param name="allowFullScreen" value="true"></param><param- name="allowscriptaccess" value="always"></param><embed- src="http://www.youtube.com/v/jj5qrHl5ZS0&hl=en_US&fs=1&rel=0"- type="application/x-shockwave-flash" allowscriptaccess="always"- allowfullscreen="true" width="550" height="450"></embed></object>- </center>---Here is the code I used to generate the video above: we first define four ways of moving the letters, with four functions, then we make a clip for each of these movements, and concatenate everything. ::-- from moviepy import *- import numpy as np-- # A nerdy tool for rotations.- rotMatrix = lambda a: np.array( [[np.cos(a),np.sin(a)],- [-np.sin(a),np.cos(a)]])--- # The letters appear from all directions- def vortex(fpos,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: fpos+400*d(t)*rotMatrix(0.5*d(t)*a).dot(v)--- # The letters appear from above- def cascade(fpos,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: fpos+v*400*d(t-0.15*i)--- # The letters arrive from the right- def arrive(fpos,i,nletters):- v = np.array([-1,0])- d = lambda t : max(0, 3-3*t)- return lambda t: fpos-400*v*d(t-0.2*i)--- # The letters 'explode'- def vortexout(fpos,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: fpos+400*d(t-0.1*i)*rotMatrix(-0.2*d(t)*a).dot(v)--- screensize = (720,460)- txtClip = TextClip('Cool effect',color='white', font="Amiri-Bold",- kerning = 5, fontsize=100)-- clips = [ CompositeVideoClip(screensize,- moveLetters(txtClip,screensize,funcpos)).- subclip(0,5)- for funcpos in [vortex, cascade, arrive, vortexout] ]-- concat(clips).to_movie('coolTextEffects.avi')-----Ok, maybe you saw it, the central function in the script above is a function called ``moveLetters``. This is the function that recognizes the letters in the text clip and make them move, which is far from trivial. So here is the code for ``moveLetters``: ::-- from skimage.morphology import label- import scipy.ndimage as ndi-- def moveLetters(txtClip,screensize, funcpos,rem_thr=500):- """- Takes the textclip,centers it, separates the letters,- sets the position of each letter according to funcpos-- funcpos : funcpos(fpos,i,nletters) where- - fpos : final position of the letter- - i : index of the letter- - nletters : total number of letters- Returns: a position function t-> (x(t),y(t))-- rem_thr : all 'letters' with size < rem_Thr will be- considered false positives and will be removed--- >>> letters = vortexLetters(txtClip,screensize,funcpos)- >>> CompositeVideoClip(screensize,letters,transparent=True)-- """-- # First place the text at the center of the clip- # This will only be useful to get the position of- # the letters in the clip- cvc = CompositeVideoClip(screensize,- [txtClip.set_pos(['center','center'])],- transparent=True)- image = cvc.get_frame(0)- mask = cvc.mask.get_frame(0)-- # segment/label the image with scikit-image's function- mat = label(image[:,:,0])- #find the positions of the objects in the image- slices = ndi.find_objects(mat)- #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- slices = sorted(slices, key = lambda s : s[1].start)--- letters = []- for i,(sy,sx) in enumerate(slices):- """ crop each letter separately and set position """- sy = slice(sy.start-1,sy.stop+1)- sx = slice(sx.start-1,sx.stop+1)- letter = ImageClip(image[sy,sx])- letter.mask = ImageClip(mask[sy,sx],ismask=True)- finalpos = np.array((sx.start,sy.start)) # final position- letter.pos = funcpos(finalpos,i,len(slices))- letters.append(letter)-- return letters-diff --git a/docs/examples/the_end.rst b/docs/examples/the_end.rstindex 2d082a73..8308c773 100644--- a/docs/examples/the_end.rst+++ b/docs/examples/the_end.rst@@ -19,25 +19,6 @@ clip there is the actual movie. The actual movie has a mask which representsa white (=opaque) circle on a black (=transparent) background. At the begining,that circle is so large that you see all the actual movie and you don't seethe "The End" clip. Then the circle becomes progressively smaller and as a-consequence you see less of the actual movie and more of the "The End" clip. ::+consequence you see less of the actual movie and more of the "The End" clip.- from moviepy import *- from scipy.interpolate import interp1d--- movie = MovieClip("./videos/badl-0006.mov", audio=False)- clip = movie.subclip(26,31).with_mask()- w,h = movie.size-- # The mask is a circle with vanishing radius r(t) = 800-200*t- mask = lambda t: cv2.circle(np.zeros((h,w)),(w/2,h/4),- max(0, int(800-200*t)), 1,-1, lineType=cv2.LINE_AA)-- clip.mask.get_frame = mask-- the_end = TextClip("The End",font="Amiri-bold",- color="white",fontsize=70).set_pos(('center','center'))-- final = CompositeVideoClip(movie.size,[the_end,clip])- final.duration = clip.duration- final.to_movie("theEnd.avi")+../../examples/the_end.pydiff --git a/docs/examples/ukulele_concerto.rst b/docs/examples/ukulele_concerto.rstnew file mode 100644index 00000000..25c27041--- /dev/null+++ b/docs/examples/ukulele_concerto.rst@@ -0,0 +1,23 @@+======================+A simple music video+======================++.. raw:: html++ <center>+ <object><param name="movie"+ value="http://www.youtube.com/v/AqGZ4JFkQTU&hl=en_US&fs=1&rel=0">+ </param><param name="allowFullScreen" value="true"></param><param+ name="allowscriptaccess" value="always"></param><embed+ src="http://www.youtube.com/v/AqGZ4JFkQTU&hl=en_US&fs=1&rel=0"+ type="application/x-shockwave-flash" allowscriptaccess="always"+ allowfullscreen="true" width="550" height="450"></embed></object>+ </center>+++This is an example, with no sound (lame for a music video), soon to be+replaced with a real music video example (the code will be 99% the same).+The philosophy of MoviePy is that for each new music video I will make,+I will just have to copy/paste this code, and modify a few lines.++.. literalinclude:: ../../examples/ukulele_concerto.pydiff --git a/docs/first_steps.rst b/docs/first_steps.rstdeleted file mode 100644index ed6d4e02..00000000--- a/docs/first_steps.rst+++ /dev/null@@ -1,13 +0,0 @@-First steps with MoviePy-========================--This section will get you started in a few minutes. You will learn more by browsing the reference manual, the cookbook, and the sourcecode (try it, it's very simple).--.. toctree::- :maxdepth: 1-- first_steps/example_code- first_steps/crash_course- first_steps/good_practice--diff --git a/docs/first_steps/crash_course.rst b/docs/first_steps/crash_course.rstdeleted file mode 100644index 593dc92e..00000000--- a/docs/first_steps/crash_course.rst+++ /dev/null@@ -1,207 +0,0 @@-A MoviePy crash-course--------------------------In this section we will give you the basics to start editing your videos.--The central objects of MoviePy are video clips. To compose movies, you start by loading video clips, you modify some of them, put them all together, and write the result to a file.--What is a video clip ?-~~~~~~~~~~~~~~~~~~~~~~~~~~--A video clip is basically an object with a ``get_frame`` attribute. ``get_frame`` is a function which for a given time ``t`` returns a picture of the clip at time ``t`` (more precisely, an array of numbers representing a picture). As an example, to play a clip frame by frame, you can (but you won't have to) write something like that: ::-- while t < clip.duration:- picture = clip.get_frame(t) # gets the picture at time ``t``- imdisplay( picture ) # display the picture- t = t + 1.0/24 # increment time- time.sleep( 1.0/24 ) # wait for 1/24 seconds--A video clip has some fundamental attributes:--- **The size** (width,height), ``clip.size``, indicates the dimensions in pixels of the clip. You can also access the clips's width and height with ``clip.w`` and ``clip.h`` respectively.-- **The duration**, ``clip.duration``, is the time after which the clip stops playing-- **The soundtrack**, ``clip.sound``, which contains the sound data (an array actually) of the clip. See :ref:`CCaudioClips`--When you put several clips together (see :ref:`CompositeVideoClips`), you may have to worry about some other attributes:--- **The position** indicates where the clip will appear if you display it as part of a bigger screen. It is actually a function which for each time ``t`` returns the position ``(x(t),y(t))`` at which the clip must appear.-- **The mask**, ``clip.mask``, is an array of numbers between 0 and 1, a 0 at some position meaning that the pixel at the same position in the picture should not be displayed. If you are not going to do anything complicated, you shouldn't worry about the mask (by default, all video clips have a mask with only ones, meaning that the picture should be completely visible). Just know that ``clip.mask`` is actually... a clip ! More precisely, its method ``clip.mask.get_frame`` returns, for a given time, the mask that should be used when blitting the clip's frame over another picture.---Classes of video clips-~~~~~~~~~~~~~~~~~~~~~~--Video clips can be of one of these sorts:--- ``MovieClip('myHolidays.mp4')`` for clips read from a movie file. See :class:`~VideoClip.MovieClip`.-- ``ImageClip('myPic.png')`` for clips displaying a picture, for an *a priori* infinite duration. See :class:`~VideoClip.ImageClip`.-- ``ColorClip((height,width),color=(R,G,B))`` for special ImageClips of a single color. See :class:`~VideoClip.ColorClip`.-- ``TextClip('Hello public',font='Impact-Regular')`` for special ImageClips representing a text. They are automatically generated using ImageMagick. See :class:`~VideoClip.TextClip`.--To that list we should add the ``CompositeVideoClips`` that are obtained by mixing several clips together (see :ref:`CompositeVideoClips`).--Finally, a clip can be of the base class :class:`~VideoClip.VideoClip`, and have any arbitrary ``get_frame`` method. For instance the following clip represents a 460x320-screen, that will go from black (color ``[1,1,1]``) to white (color ``[255,255,255]``) in 255 seconds. ::-- import numpy- from moviepy import *- dark_picture = np.ones((320,460,3))- def custom_get_frame(t):- return min( int(t) , 255 ) * dark_picture- clip = VideoClip().set_get_frame(custom_get_frame)---Modifying a clip-~~~~~~~~~~~~~~~~--You will find many pre-implemented methods to modify a clip in the reference manual. For instance ``clip.subclip(15,20)`` returns the part of ``clip`` that is playing between 15 seconds and 20 seconds, ``clip.resize((width, height))`` will change the resolution of the clip, while ``clip.crop`` will enable you to keep only a region of the clip and ``clip.speedx(0.5)`` will make your clip play two times slower. When it is relevant, these methods are also applied to the sound and the mask of the clip, so that you don't have to worry about modifying these.---In MoviePy **no modification of a clip occurs inplace**, which means that the result of ``clip.resize``, ``clip.speedx``, etc., will be a new clip and the original clip will be untouched. ::-- clip = MovieClip('myHolidays.mp4')- clip.resize((460,320)) # ``clip`` is NOT modified- clip = clip.resize((460,320)) # ``clip`` is modified--Another important aspect is that modified clips are just *special views* of the original clip, they do not carry all the video data with them. Actually, the *real* modifications are only performed when you are rendering the clip (see :ref:`renderingAClip`). This means that all the clip objects that you will create through modifications of other clips take virtually no place in the memory and are created instantly.--Apart from the pre-implemented modifications, you can modify a clip as you want using custom filters. You can change the timeline of the clip like this: ::-- modifiedClip1 = myClip.fl_time(lambda t: 3*t)- modifiedClip2 = myClip.fl_time(lambda t: 1+sin(t))--Now the clip ``modifiedClip1`` plays the same as ``myClip``, only three times faster, while ``modifiedClip2`` will play ``myClip`` by oscillating between the times t=0s and t=2s. Note that in the last case you have created a clip of infinite duration (which is not a problem for the moment).--You can also modify the display of a clip. The following takes a clip and inverts the green and blue channels: ::-- modifiedClip = myClip.fl_image(lambda im: im[:,:,[0,2,1]])--Finally, you may want to process the clip by taking into account the time and the picture at the same time. This is possible with ``clip.fl``. The filter must be a function which takes two arguments and returns a picture. the fist argument is a ``get_frame`` method (i.e. a function which given a time returns a picture), and the second argument is the time. ::-- modifiedClip = myClip.fl(lambda gf,t: np.minimum(int(t),gf(2*t))--This last one is a little complicated to grasp. ``modifiedClip`` is now a version of ``myClip``, only two times faster, and with some sort of a fade-in effect.-----.. _CompositeVideoClips:--Composite video clips-~~~~~~~~~~~~~~~~~~~~~--Composite video clips are video clips which will display the contents of several other video clips. The simplest compositing is concatenation with :meth:`~VideoClip.concat`: ::-- video = concat([clip1,clip2,clip3])--Now ``myVideo`` is a clip that plays the clips 1, 2, and 3 one after the other. You can also play a transition clip between the clips with the option ``transition=myClip``.--Next, you have the composite videoclip: ::-- video = CompositeVideoClip(clip1.size, [clip1,clip2,clip3])--Now ``myVideo`` is a clip that has the size of ``clip1``, and plays ``clip1``, and ``clip2`` *on top of* ``clip1``, and ``clip3`` on top of-``clip1``, and ``clip2``. Of course, if ``clip2`` and ``clip3`` have the same size as ``clip1``, then only ``clip3``, which is on top, will be-visible in the video... unless ``clip3`` and ``clip2`` have masks which hide parts of them.--You can set the starting time of each clip as follows: ::-- video = CompositeVideoClip(clip.size, [clip1,clip2,clip3])--Because the three clips overlap, we can make them appear with a fading-in effect. Here we go for fadein effects that last 1.5 seconds: ::-- video = CompositeVideoClip(clip1.size, [clip1, # starts at t=0- clip2.set_start(50).fadein(1.5),- clip3.set_start(90).fadein(1.5)])--Finally, if ``clip2`` and ``clip3`` are smaller than ``clip1``, you can decide where they will appear: ::-- video = CompositeVideoClip(clip1.size,- [clip1,- clip2.set_pos((45,150)),- clip3.set_pos((90,100))])--Note that there are many ways to specify the position: ::-- clip2.set_pos((45,150)) # x=45, y=150-- # clip2 is horizontally centered, and at the top of the picture- clip2.set_pos(("center","top"))-- # clip2 is at 40% of the width, 70% of the height:- clip2.set_pos((0.4,0.7), relative=True)-- # clip2's position is horizontally centered, and moving up !- clip2.set_pos(lambda t: ('center', 50+t) )--Be careful when indicating the position that the ``y`` position has its-zero at the top of the picture:--.. figure:: videoWH.jpeg----.. _renderingAClip:--Rendering a video clip-~~~~~~~~~~~~~~~~~~~~~~~--The ``duration`` attribute must be set (with ``clip.set_duration``) to be able to preview or write the movie to a file (some clips, like clips displaying a picture, have *a priori* an infinite duration).--To display one frame of the clip, you type one of these: ::-- myClip.show() # shows the first frame of the clip- myClip.show(10.5) # shows the frame of the clip at t=10.5s- myClip.show(10.5,frontend="matplotlib") # show in a matplotlib window--To preview the clip, you type::-- myClip.preview() # preview with default fps=15- myClip.preview(fps=25)- myClip.preview(fps=15, audio=False) # Play the clip with no sound.--It is important to note that the ``fps`` can be any number, independently of the ``fps`` of your different sources.--To write a clip as a video file, use ::-- myClip.to_movie("myEditedMovie.avi") # default codec: 'DIVX' fps: 24- myClip.to_movie("myEditedMovie.avi",fps=24, codec='raw') # raw movie- myClip.to_movie("myEditedMovie.avi",audio=False) # don't render the audio.--The codec *DIVX* will produce very light yet good quality movies, while the *raw* codec will produce very large movies with perfect quality. Many other codecs are available.---.. _CCaudioClips:--Audio clips-~~~~~~~~~~~~~--The second important objects of MoviePy are the audio clips. If ``myHolidays.mp4`` is a video with sound, then ::-- clip = MovieClip('myHolidays.mp4', audio=True)--will create a clip with a ``clip.sound`` attribute which is an audio clip. This is the sound that you will hear if you render the clip with ``clip.preview`` or ``clip.to_movie``. You can also create an audio clip from a sound file and then attach it to a video clip: ::-- audio = SoundClip('mySong.wav')- video = MovieClip('myHolidays.mp4').set_audio(audio)--Like video clips, audio clips can be cut (with ``clip.subclip``) modified (with for instance ``clip.volumex`` which multiplies the volume) and combined (with ``CompositeAudioClip``). But most of the time, MoviePy will do that for you:--- When you cut a video clip with ``videoclip.subclip(20,25)`` then the sound will also be cut, i.e. the resulting clip will have an audio clip ``videoclip.audio.subclip(20,25)``.-- When you put several clips together in a CompositeVideoClip, then the sound of the CompositeVideoClip will be the composition of the sounds of the different video clips.--For an example, you can refer to :ref:`soundexample`. Like video clips, sound clips have a ``get_frame`` attribute, and creating new audio clips by modifying or putting together other audio clips does not take place in the memory. The actual sounds of the audio clips are only computed when we ask to play them or to write them to a file. You can do that as follows: ::-- audioclip.preview() # default fps: 22050- audioclip.preview(fps=44100)- audioclip.to_soundfile('myclip.wav',fps=44100) #default fps: 22050--Going further-~~~~~~~~~~~~~~--Now you should understand the scripts given in :ref:`examples`, and you should be able to write your own scripts. To go further and learn about all the available options and functionalities of MoviePy, see the :ref:`cookbook` and the reference manual.-----diff --git a/docs/first_steps/example_code.rst b/docs/first_steps/example_code.rstdeleted file mode 100644index 277d977d..00000000--- a/docs/first_steps/example_code.rst+++ /dev/null@@ -1,30 +0,0 @@-Example code---------------We start with some code to show you the MoviePy syntax. In a typical script, you load or generate some clips, modify them, combine them, and write the result to a video file.--We will now load a movie of my last holidays, lower the volume, add a title in the center of the video for the ten first seconds, and write the result in a file: ::-- from moviepy import *-- # Load myHolidays.mp4 and select the subclip 00:00:50 - 00:00:60- clip = MovieClip("myHolidays.mp4", audio=True).subclip(50,60)-- # Reduce the sound volume (volume x 0.8)- clip.sound = clip.sound.volumex(0.8)-- # Generate a text clip. You can customize the font, color, etc.- txt_clip = TextClip("My Holidays 2013",fontsize=70,color='white')--- # Say that you want it to appear 10s at the center of the screen- txt_clip = txt_clip.set_pos(('center','center')).set_duration(10)-- # Overlay the text clip on the first video clip- video = CompositeVideoClip(clip.size, [clip, txt_clip])-- # Write the result to a file. The default encoding will be DIVX.- video.write("myHolidays_edited.avi",fps=24)--See ? That was easy !-diff --git a/docs/first_steps/good_practice.rst b/docs/first_steps/good_practice.rstdeleted file mode 100644index ec9d8f2d..00000000--- a/docs/first_steps/good_practice.rst+++ /dev/null@@ -1,31 +0,0 @@-.. _goodPractices:--Good Practices------------------MoviePy works fine on my 1.5 petaflops supercomputer, but like for any other video software, the bottleneck is the heavy computations required to produce several pictures per second. If you write a very complex clip, the previews and the rendering to a file may be very slow. Here are a few tricks to ease things:---- Use an interactive shell, like IPython or, better, the IPython notebook. If you don't know these, you don't know what you are missing !-- Prefer the clip.show() option, and use it a lot. Only use clip.preview() when really necessary.-- For the moment the audio is generated for each preview and before the preview. So if you want to preview a lengthy clip with sound, it may take a few seconds before the preview actually launches, and the sound may take lots of place in memory. Therefore, it is advised to only preview small bits of a movie with audio. Reducing the audio fps when previewing reduces the problem.-- If some part of your video is particularly complex and long to render, save this part as either a raw video (enables to save the sound) or in a directory of pictures (enables to save the mask), then use this video instead of this part's script. ::-- myVideo.to_movie('save.avi',fps=24,codec='raw', audio=True)- # or- myVideo.to_directory('./mySaveDirectory',fps=24)--- If you are going to use extracts of big movies with sound, do NOT write ::-- # "Charade" is a 2h00 long movie- myVideo = MovieClip("charade.mp4",sound=True).subclip(30,35)-- The reason is that in the snippet above the whole sound of the movie will be converted into a .wav file and then loaded into the memory. Instead, extract the subclip between t=30s and t=35s as a new video file and use this one instead. Like this ::-- import moviepy.ffmpeg as mf- mf.extract_subclip("charade.mp4",30,35, "charadeSUB30_35.mp4")- myVideo = MovieClip("charadeSUB30_35.mp4",sound=True)--- Prototype: design your clips separately. If your composition involves a clip that is not finished yet, replace it temporarily with a basic color clip.-- There are often several ways to produce a same effect with MoviePy, but some ways are faster. For instance don't apply effects to a whole screen video if you are only using one region of the screen afterwards: first crop the selected region, then apply your effects.-- [wishful thinking] Check on the internet or in the examples of this documentation that what you do hasn't been done before. Code shared on the internet has more chances to be optimized.diff --git a/docs/forDevelopers.rst b/docs/forDevelopers.rstdeleted file mode 100644index f5d93a1a..00000000--- a/docs/forDevelopers.rst+++ /dev/null@@ -1,53 +0,0 @@-.. forDevs:--===============================-For developpers-===============================---TODO list---------------Ideas of improvement (suggestions, help and commits are welcome !):--- Find users.-- Improve the ``set_pos`` functions, give it functionalities inspired from CSS/HTML, like margin-right, etc...-- Improve readability/naming.-- Make an installer for all the dependencies ?---Discussion of the dependencies----------------------------------I have found that complicated dependencies are a main reason why people get-discouraged by a software, so I take all the advices on the subject.---Movie writing-~~~~~~~~~~~~~~~~~~~~~~~--To write a movie, I used to generate pictures of the frames and then put them together using ffmpeg, because this is what matplotlib does. But it can be up to fifty times slower than writing the movie directly with OpenCV, and it is less memory efficient.--However, I like how you can tune the quality of the movie with ffmpeg, and I can't think of something else to merge sound and image. I know there is a war between ffmpeg/avconv/mencoder. I think ffmpeg is the most spread software. And no, it's not deprecated.--Movie rendering-~~~~~~~~~~~~~~~~~~~~~~~--For movie previews I am using Pygame instead of the original OpenCV frontend because Pygame-can also generate sound.----Movie and image manipulation-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--The python package SimpleCV is an attempt at making OpenCV easier to use. It is totally cool, but the OpenCV devs are also trying to make it easier so they always make a lot of changes which break SimpleCV. They use the Python Imaging Library for image processing.--The package Wand (a Python binder for ImageMagick) is nice and is starting to accept numpy array images input/output.---Sound-~~~~~~~--The python package Pydub is really good but working with numpy arrays gives more freedom so I stick with Scipy.-diff --git a/docs/index.rst b/docs/index.rstindex e37619cf..905607f5 100644--- a/docs/index.rst+++ b/docs/index.rst@@ -6,9 +6,9 @@ MoviePy is a Python module for script-based movie editing, which enables basic oimport osfrom moviepy import *files = sorted( os.listdir("clips/") )- clips = [ MovieClip('clips/'+f,audio=False) for f in files]- video = concat(clips, transition = MovieClip("logo.avi"))- video.to_movie("demos.avi",fps=25, codec='DIVX')+ clips = [ VideoFileClip('clips/%s'%f) for f in files]+ video = concatenate(clips, transition = VideoFileClip("logo.avi"))+ video.to_videofile("demos.avi",fps=25, codec="mpeg4").. raw:: html@@ -31,17 +31,15 @@ User's Guide--------------.. toctree::- :maxdepth: 2+ :maxdepth: 1install- first_steps- examples- cookbook- ref- forDevelopers+ crash_course/crash_course+ examples/examples+ ref/ref-MoviePy is a (still experimental) open source software written by Zulko_ and released under the MIT liscence. Everyone is welcome to help improve the project, fork it, blog on it, share new effects, etc...+MoviePy is a (still experimental) open source software written by Zulko_ and released under the MIT licence. Everyone is very welcome to help improve the project, fork it, blog on it, share code for new effects, etc... The more, the merrier !For troubleshooting and bug reports, the best for now is to ask on Stackoverflow_ (it will advertize for the project :) ) or on the Github project page.diff --git a/docs/install.rst b/docs/install.rstindex c57539d5..7119102e 100644--- a/docs/install.rst+++ b/docs/install.rst@@ -1,35 +1,61 @@Download and Installation-----------------------------+==========================-You can `download MoviePy`_ on its Github repository.+Core dependencies+-------------------++MoviePy cannot run without these dependencies:++- The software ffmpeg_ is needed for writing, reading, converting the sound and the video. Normally any version of FFMPEG should work but it is recommended to use a recent version for better results.+- `Numpy`_ is needed for image and sound manipulation+- The Decorator_ module is used in the MoviePy code for better code readability++Numpy and Decorator will be automatically installed during MoviePy's installation if not present on your computer. As for ffmpeg, you can either install it or save the binary files in any folder and specify the path to these folders before installing MoviePy (see manual_install_).++Installation with PIP+------------------------+Coming soon.+++.. _manual_install:++Manual installation+----------------------++If you want the cutting edge version you can `download MoviePy`_ on its Github repository.Just unzip everything in one folder, open a terminal and type ::sudo python setup.py install+Before doing that, you should make sure that MoviePy can locate ffmpeg on your computer. To do that, run the script ``moviepy/conf.py``. It it fails, then you must enter the path in the first line of this file ::++ FFMPEG_BINARY = path/to/your/ffmpeg-This should install the python packages listed below, **but NOT OpenCV**, which you will have to download and install manually (see below).++(Not so) Optional dependencies+--------------------------------MoviePy is a very small program but it relies on many existing Python packages:+You are not obliged to install these but for many uses MoviePy will scream at you and say that the package or the software is missing. All these dependencies can be installed any time after the installation of MoviePy.-- `OpenCV 2.4.6`_ or more recent, to read and write movie files.-- PyGame_ for video and sound previews-- `Scipy and Numpy`_, for image and sound manipulation-- `Scikit Image`_ for advanced image manipulation-- The Decorator_ module for better code readability+- PyGame_ is needed for video and sound previews (really essential for advanced editing).+- imageMagick_ is needed for all text generation, GIF support, and much more in the future.-MoviePy also needs some external software that you will need to install:+There are many packages for image manipulation/processing in python. Most effects are coded such that none of these packages are needed, or such that having at least one of these packages is sufficient.-- ffmpeg_, for writing movies and many other useful operations.-- imageMagick_ for text generation, GIF support, and much more in the future.+- Scipy is needed for many advanced functionalities (tracking, segmenting, etc.)+- `Scikit Image`_ may be needed for some advanced image manipulation.+- The Python Imaging Library is not used yet (I don't like the copyright) but it is coming.+- `OpenCV 2.4.6`_ (which provides the python package ``cv2``) or more recent may be needed for some advanced image manipulation. See below for the installation of OpenCV.++If you are on linux, these will surely be in your repos.-All these are normally easy to install (on linux, they will certainly be in your repos).Installing OpenCV 2.4.6-~~~~~~~~~~~~~~~~~~~~~~~~+~~~~~~~~~~~~~~~~~~~~~~~~~-That will depend on your system. It seems easy for Windows. On linux, here is what I found on the Internet:+OpenCV is very optional, its installation is not always simple and I found it to be unstable, be warned. The installation seems easy for Windows. On linux, here is what I found on the Internet:- Remove any other version of OpenCV if you installed it through a package manager.- Unzip the source code of `OpenCV 2.4.6`_ in some folder. open a terminal in this folder.@@ -57,7 +83,7 @@ You can check if it worked by opeing a Python console and typing ::import cv2print cv2.__version__-+Advice: do not throw your ``release`` folder away. If later you have strange bugs with OpenCV involving ``.so`` files, just redo the ``sudo make install`` step.@@ -67,7 +93,7 @@ You can check if it worked by opeing a Python console and typing ::.. _`download MoviePy`: https://github.com/Zulko/moviepy.. _`OpenCV 2.4.6`: http://sourceforge.net/projects/opencvlibrary/files/.. _Pygame: http://www.pygame.org/download.shtml-.. _`Scipy and Numpy`: http://www.scipy.org/install.html+.. _`Numpy`: http://www.scipy.org/install.html.. _`Scikit Image`: http://scikit-image.org/download.html.. _Decorator: https://pypi.python.org/pypi/decoratordiff --git a/docs/readme.txt b/docs/readme.txtdeleted file mode 100644index a641b0f2..00000000--- a/docs/readme.txt+++ /dev/null@@ -1,27 +0,0 @@-Installation----------------MoviePy is very light (~1000 lines of code) but it uses many Python libraries-- `OpenCV 2.4.6`_ to read the movies-- PyGame_ for video/sound previews-- `Scipy and Numpy`_, for image/sound manipulation-- `Scikit Image`_ for advanced image manipulation-- The Decorator_ module for better code readability--And needs some software:-- avconv, the "new ffmpeg", for writing movies and many useful operations.-- imageMagick for text generation (and much more in the future)--All these are normally easy to install (on linux, most of these will be in your repos).--Then you open a console in the moviepy source directory and type-- sudo python setup.py install--.. _`OpenCV 2.4.6`: http://sourceforge.net/projects/opencvlibrary/files/-.. _Pygame: http://www.pygame.org/download.shtml-.. _`Scipy and Numpy`: http://www.scipy.org/install.html-.. _`Scikit Image`: http://scikit-image.org/download.html-.. _Decorator: https://pypi.python.org/pypi/decorator-diff --git a/docs/ref.rst b/docs/ref.rstdeleted file mode 100644index 7919288e..00000000--- a/docs/ref.rst+++ /dev/null@@ -1,10 +0,0 @@-Reference Manual-================--.. toctree::- :maxdepth: 2-- ref/Clip_ref- ref/VideoClip_ref- ref/AudioClip_ref- ref/ffmpegdiff --git a/docs/ref/AudioClip_ref.rst b/docs/ref/AudioClip.rstsimilarity index 61%rename from docs/ref/AudioClip_ref.rstrename to docs/ref/AudioClip.rstindex adeb23bb..53751845 100644--- a/docs/ref/AudioClip_ref.rst+++ b/docs/ref/AudioClip.rst@@ -7,14 +7,14 @@ AudioClip:class:`AudioClip`==========================-.. autoclass:: AudioClip.AudioClip+.. autoclass:: moviepy.audio.AudioClip.AudioClip:members::show-inheritance:-:class:`SoundClip`+:class:`AudioFileClip`==========================-.. autoclass:: AudioClip.SoundClip+.. autoclass:: moviepy.audio.io.AudioFileClip.AudioFileClip:members::show-inheritance:@@ -22,7 +22,7 @@ AudioClip:class:`CompositeAudioClip`================================-.. autoclass:: AudioClip.CompositeAudioClip+.. autoclass:: moviepy.audio.AudioClip.CompositeAudioClip:members::show-inheritance:diff --git a/docs/ref/Clip_ref.rst b/docs/ref/Clip.rstsimilarity index 100%rename from docs/ref/Clip_ref.rstrename to docs/ref/Clip.rstdiff --git a/docs/ref/VideoClip_ref.rst b/docs/ref/VideoClip.rstsimilarity index 55%rename from docs/ref/VideoClip_ref.rstrename to docs/ref/VideoClip.rstindex 2a781b56..708adb3c 100644--- a/docs/ref/VideoClip_ref.rst+++ b/docs/ref/VideoClip.rst@@ -7,28 +7,28 @@ VideoClip:class:`VideoClip`==========================-.. autoclass:: VideoClip.VideoClip+.. autoclass:: moviepy.video.VideoClip.VideoClip:members::show-inheritance:-:class:`MovieClip`-==========================+:class:`VideoFileClip`+-------------------------.. autoclass:: VideoClip.MovieClip+.. autoclass:: moviepy.video.io.VideoFileClip.VideoFileClip:members::show-inheritance::class:`ImageClip`==========================-.. autoclass:: VideoClip.ImageClip+.. autoclass:: moviepy.video.ImageClip.ImageClip:members::show-inheritance::class:`ColorClip`-------------------.. autoclass:: VideoClip.ColorClip+.. autoclass:: moviepy.video.ImageClip.ColorClip:members::show-inheritance:@@ -36,18 +36,18 @@ VideoClip:class:`TextClip`----------------------.. autoclass:: VideoClip.TextClip+.. autoclass:: moviepy.video.ImageClip.TextClip:members::show-inheritance::class:`CompositeVideoClip`============================-.. autoclass:: VideoClip.CompositeVideoClip+.. autoclass:: moviepy.video.compositing.CompositeVideoClip.CompositeVideoClip:members::show-inheritance:Useful Methods---------------.. automethod:: moviepy.VideoClip.concat+.. automethod:: moviepy.video.compositing.concatenate.concatenatediff --git a/docs/ref/audiofx.rst b/docs/ref/audiofx.rstnew file mode 100644index 00000000..37354fe4--- /dev/null+++ b/docs/ref/audiofx.rst@@ -0,0 +1,11 @@+.. ref_audiofx:++************+audio.fx+************+This module regroups functions meant to be used with ``audio.fx`` or ``videoclip.fx``. When you type ``from moviepy import *``, the module ``audio.fx`` is loaded as ``afx`` and you can use ``afx.volumex`` etc.+++.. automodule:: moviepy.audio.fx+ :members:+ :show-inheritance:diff --git a/docs/ref/audiotools.rst b/docs/ref/audiotools.rstnew file mode 100644index 00000000..3309b674--- /dev/null+++ b/docs/ref/audiotools.rst@@ -0,0 +1,7 @@+.. ref_audiotools:++************+audio.tools+************++Currently emptydiff --git a/docs/cookbook/gradient.jpeg b/docs/ref/bideotools_gradient.jpegsimilarity index 100%rename from docs/cookbook/gradient.jpegrename to docs/ref/bideotools_gradient.jpegdiff --git a/docs/ref/decorators.rst b/docs/ref/decorators.rstnew file mode 100644index 00000000..ad314d3b--- /dev/null+++ b/docs/ref/decorators.rst@@ -0,0 +1,10 @@+.. ref_decorators:++************+Decorators+************+These decorators are implemented to ease the writing of methods and effects in MoviePy++.. automodule:: moviepy.decorators+ :members:+ :show-inheritance:diff --git a/docs/ref/ffmpeg.rst b/docs/ref/ffmpeg.rstindex d1aae0d2..df2edfac 100644--- a/docs/ref/ffmpeg.rst+++ b/docs/ref/ffmpeg.rst@@ -1,9 +1,9 @@.. _ffmpegTools:-FFMPEG-related functions+FFMPEG tools-----------------------------.. automodule:: ffmpeg+.. automodule:: moviepy.video.io.ffmpeg:members::undoc-members::show-inheritance:diff --git a/docs/ref/ref.rst b/docs/ref/ref.rstnew file mode 100644index 00000000..03558749--- /dev/null+++ b/docs/ref/ref.rst@@ -0,0 +1,18 @@+Reference Manual+================++The documentation may be a little messy for the moment, it will get better with time.++.. toctree::+ :maxdepth: 2++ Clip+ VideoClip+ videofx+ videotools+ AudioClip+ audiofx+ audiotools+ ffmpeg+ decorators+diff --git a/docs/ref/videofx.rst b/docs/ref/videofx.rstnew file mode 100644index 00000000..20e7d14b--- /dev/null+++ b/docs/ref/videofx.rst@@ -0,0 +1,11 @@+.. ref_videofx:++************+video.fx+************+This module regroups functions meant to be used with ``videoclip.fx``. When you type ``from moviepy import *``, the module ``video.fx`` is loaded as ``vfx`` and you can use ``vfx.colorx``, ``vfx.resize``, etc.+++.. automodule:: moviepy.video.fx+ :members:+ :show-inheritance:diff --git a/docs/ref/videotools.rst b/docs/ref/videotools.rstnew file mode 100644index 00000000..9338a776--- /dev/null+++ b/docs/ref/videotools.rst@@ -0,0 +1,31 @@+.. ref_videotools:++************+video.tools+************++This module regroups advanced, useful (and less useful) functions for editing videos.++Drawing+--------+.. automodule:: moviepy.video.tools.drawing+ :members:+ :show-inheritance:++Segmenting+----------+.. automodule:: moviepy.video.tools.segmenting+ :members:+ :show-inheritance:++Tracking+--------+.. automodule:: moviepy.video.tools.tracking+ :members:+ :show-inheritance:++Credits+--------+.. automodule:: moviepy.video.tools.credits+ :members:+ :show-inheritance:diff --git a/docs/cookbook/credits.jpeg b/docs/ref/videotools_credits.jpegsimilarity index 100%rename from docs/cookbook/credits.jpegrename to docs/ref/videotools_credits.jpegdiff --git a/moviepy/AudioClip.py b/moviepy/AudioClip.pydeleted file mode 100644index 11810fca..00000000--- a/moviepy/AudioClip.py+++ /dev/null@@ -1,173 +0,0 @@-import time-import os-from copy import copy, deepcopy-import shutil--import numpy as np-from scipy.io import wavfile--import pygame as pg-import ffmpeg--from Clip import Clip, requires_duration---class AudioClip(Clip):-- """-- Base class for audio clips. See ``SoundClip`` and ``CompositeSoundClip``- for usable classes.-- :ivar get_frame: A function `t-> frame at time t`. the frame does not- mean much for a sound, it is just an integer.-- :ivar nchannels: Number of channels (one or two for mono or stereo)- of the sound.-- :ivar nbits: Number of bits per frame (the more the better).- """-- def __init__(self):- Clip.__init__(self)-- @requires_duration- def toSoundClip(self, fps=24000):- """ Transforms the clip into a soundclip by (audio clip with a- precomputed sound array """-- tt = np.linspace(0, self.duration, self.duration * fps)[:-1]- arr = np.array(map(self.get_frame, tt)).astype('int16')- return SoundClip(arr, fps)-- @requires_duration- def preview(self, fps=22050, sleep=True):- """ Plays the sound clip with pygame. If ``sleep=True`` the- program is freezed while the sound is playing (necessary- when the sound is playing alone without video)."""- pg.mixer.quit()- array = self.toSoundClip(fps).array- pg.mixer.init(fps, -8 * self.nbits, self.nchannels, 4096)- snd = pg.sndarray.make_sound(array)- snd.play()- if sleep:- time.sleep(self.duration)-- @requires_duration- def to_soundfile(self, filename=None, fps=22050):- """ Writes the soundclip to a .wav file """- array = self.toSoundClip(fps).array- wavfile.write(filename, fps, array)-- def volumex(self, factor):- """ Returns an audioclip playing the same sound but with a volume- multiplied by the ``factor``. """- return self.fl(lambda gf, t: factor * gf(t))-- def fadein(self, duration):- """ Return a sound 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 self.fl(fading)-- @requires_duration- def 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: min(- 1.0 * (self.duration - t) / duration, 1) * gf(t)- return self.fl(fading)-- @property- def nchannels(self):- return len(list(self.get_frame(0)))-- @property- def nbits(self):- return self.get_frame(0).itemsize---class SoundClip(AudioClip):-- """-- An audio clip read from a sound file, or an array.-- :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 fps: If ``snd`` is an array, this parameter is required.- :param bitrate: If ``snd`` is not a .wav, this prameter is required- for the conversion.-- >>> snd = SoundClip("song.wav")- >>> snd = SoundClip("song.mp3", fps = 44100, bitrate=3000)- >>> snd = SoundClip(mySoundArray,fps=44100) # from a numeric array-- """-- def __init__(self, snd, fps=None, bitrate=3000):-- Clip.__init__(self)-- if isinstance(snd, str):- if not snd.endswith('.wav'):- temp = 'temp.wav'- ffmpeg.extract_sound(snd, temp, fps, bitrate)- fps, arr = wavfile.read(temp)- # os.remove(temp)- else:- fps, arr = wavfile.read(snd)-- self.array = arr- self.fps = fps- else:- self.array = snd- self.fps = fps-- self.duration = 1.0 * len(self.array) / self.fps-- def gf(t):- i = int(self.fps * t)- if i < 0 or i >= len(self.array):- return 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- self.compute_duration()-- def gf(t):- return sum([0*self.clips[0].get_frame(0)]+- [c.get_frame(t - c.start)- for c in self.playing_clips(t)])-- self.get_frame = gf-- def compute_duration(self):- ends = [c.end for c in self.clips]- if not any([(e is None) for e in ends]):- self.duration = max(ends)-- def playing_clips(self, t=0):- return [c for c in self.clips if c.is_playing(t)]diff --git a/moviepy/Clip.py b/moviepy/Clip.pyindex 5e04acd4..51abeb8e 100644--- a/moviepy/Clip.py+++ b/moviepy/Clip.py@@ -1,41 +1,14 @@-import decorator-from copy import copy, deepcopy+"""+This module implements the central object of MoviePy, the Clip, and+all the methods that are common to the two subclasses of Clip, VideoClip+and AudioClip.+"""+from copy import copy+import numpy as np-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)---#-#-# C L I P-#-#+from moviepy.decorators import ( apply_to_mask, apply_to_audio,+ time_can_be_tuple)class Clip:@@ -56,12 +29,21 @@ class Clip:are infinite and do not have any duration."""++ # prefix for all tmeporary video and audio files.+ # You can overwrite it with+ # >>> Clip._TEMP_FILES_PREFIX = "temp_"++ _TEMP_FILES_PREFIX = 'TEMP_MPY_'def __init__(self):self.start = 0self.end = Noneself.duration = None++ def copy(self):+ return copy(self)def fl(self, fl, applyto=[], keep_duration=True):"""@@ -93,9 +75,9 @@ class Clip:newclip = self.set_get_frame(lambda t: fl(gf, t))if not keep_duration:- newclip.duration = None- newclip.end = None-+ newclip.duration = None+ newclip.end = None+if isinstance(applyto, str):applyto = [applyto]@@ -107,7 +89,8 @@ class Clip:return newclip- def fl_time(self, t_func, applyto=['mask', 'sound'], keep_duration=False):++ def fl_time(self, t_func, applyto=[], keep_duration=False):"""Returns a clip playing the content of the current clip but with amodified timeline, time ``t`` being replaced by another@@ -131,32 +114,60 @@ class Clip:return self.fl(lambda gf, t: gf(t_func(t)), applyto,keep_duration=keep_duration)++ def fx(self, func, *args, **kwargs):+ """++ Returns the result of ``func(self, *args, **kwargs)``.+ for instance++ >>> newclip = clip.fx(resize,0.2,method='bilinear')++ is equivalent to++ >>> newclip = resize(clip,0.2, method='bilinear')++ The motivation of fx is to keep the name of the effect near its+ parameters, when the effects are chained:++ >>> from moviepy.fx import volumex, resize, mirrorx+ >>> clip.fx( volumex, 0.5).fx( resize, 0.3).fx( mirrorx )+ >>> # Is equivalent, but clearer than+ >>> resize( volumex( mirrorx( clip ), 0.5), 0.3)++ """++ return func(self, *args, **kwargs)+@apply_to_mask@apply_to_audio- def set_start(self, t):+ @time_can_be_tuple+ def set_start(self, t, change_end=True):"""Returns a copy of the clip, with the ``start`` attribute set to ``t``.- Also sets the duration of the returned clip's mask and audio, if any.+ Automatically changes the end of the clip if the clip has a duration+ and ``change_end`` is True. Else, sets the duration of the+ returned clip's mask and audio, if any."""- newclip = copy(self)+ newclip = self.copy()newclip.start = t- if newclip.end is None:- if newclip.duration != None:- newclip.end = t + newclip.duration- else:+ if (newclip.duration != None) and change_end:+ newclip.end = t + newclip.duration+ elif (newclip.end !=None):newclip.duration = newclip.end - newclip.startreturn newclip@apply_to_mask@apply_to_audio+ @time_can_be_tupledef set_end(self, t):"""Returns a copy of the clip, with the ``end`` attribute set to ``t``.Also sets the duration of the returned clip's mask and audio, if any."""- newclip = copy(self)+ newclip = self.copy()newclip.end = tif newclip.start is None:if newclip.duration != None:@@ -168,6 +179,7 @@ class Clip:@apply_to_mask@apply_to_audio+ @time_can_be_tupledef set_duration(self, t):"""Returns a copy of the clip, with the ``duration`` attribute set@@ -188,25 +200,44 @@ class Clip:newclip = copy(self)newclip.get_frame = gfreturn newclip-++ @time_can_be_tupledef is_playing(self, t):"""Return true if t is between the start and the end of the clip """+ if isinstance(t, np.ndarray):+ t = t.max()return (((self.end is None) and (t >= self.start)) or(self.start <= t <= self.end))+ @time_can_be_tuple@apply_to_mask@apply_to_audiodef subclip(self, ta=0, tb=None):"""Returns a clip playing the content of the current clip- between times ``ta`` and ``tb`` (in seconds). If tb is not+ between times ``ta`` and ``tb`` (in seconds). If ``tb`` is notprovided, plays until the end of the clip, potentially forever.- If ``tb`` is provided, the duration of the returned clip is- set automatically.+ If ``tb`` is a negative value, ``tb`` is set to+ `` clip.duration - tb. ``, for instance:++ >>> # cut the last two seconds of the clip:+ >>> newclip = clip.subclip(0,-2)++ If ``tb`` is provided or if the clip has a duration attribute,+ the duration of the returned clip is set automatically.The same effect is applied to the clip's audio and mask if any."""- newclip = self.fl_time(lambda t: t + ta)++ newclip = self.fl_time(lambda t: t + ta, applyto=[])+ if (tb is None) and (self.duration != None):+ tb = self.duration+ elif tb<0:+ if self.duration is None:+ print ("Error: subclip with negative times can only be"++ "be taken from clips with a ``duration``")+ else:+ tb = self.duration - tbif (tb != None):return newclip.set_duration(tb - ta)else:@@ -214,6 +245,7 @@ class Clip:@apply_to_mask@apply_to_audio+ @time_can_be_tupledef cutout(self, ta, tb):"""Returns a clip playing the content of the current clip but@@ -228,37 +260,3 @@ class Clip:return newclip.set_duration(self.duration - (tb - ta))else:return newclip-- @requires_duration- @apply_to_mask- @apply_to_audio- def time_mirror(self):- """- Returns a clip that plays the current clip backwards (who said- useless ???). 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)-- @requires_duration- @apply_to_mask- @apply_to_audio- def loop(self):- """- Returns a clip that plays the current clip in an infinite loop.- """- return self.fl_time(lambda t: t % self.duration)-- @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 newclipdiff --git a/moviepy/VideoClip.py b/moviepy/VideoClip.pydeleted file mode 100644index 754efacb..00000000--- a/moviepy/VideoClip.py+++ /dev/null@@ -1,1226 +0,0 @@-import time-import os-import shutil-import subprocess-from copy import copy--import numpy as np-from skimage.io import imread, imshow-import cv2-import pygame as pg-import ffmpeg--from Clip import Clip, apply_to_mask, requires_duration-from AudioClip import SoundClip, CompositeAudioClip----# We start with an horrible hack due to be able to find the right-# constants across the different OpenCV versions.--try:- CAP_PROP_POS_FRAMES = cv2.CAP_PROP_POS_FRAMES- CAP_PROP_FPS = cv2.CAP_PROP_FPS- CAP_PROP_FRAME_COUNT = cv2.CAP_PROP_FRAME_COUNT-except:- try:- CAP_PROP_POS_FRAMES = cv2.cv.CV_CAP_PROP_POS_FRAMES- CAP_PROP_FPS = cv2.cv.CV_CAP_PROP_FPS- CAP_PROP_FRAME_COUNT = cv2.cv.CV_CAP_PROP_FRAME_COUNT- except:- print "Error: unable to find CAP_PROP_POS_FRAMES etc."- raise---try:- FOURCC = cv2.cv.FOURCC-except:- try:- FOURCC = cv2.VideoWriter_fourcc- except:- print "Error : unable to find FOURCC."- raise--# End of the hack-------# Initiates a Pygame window-pg.init()-pg.display.set_caption('MoviePy')--#-#-# TOOL FUNCTIONS-#-#---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 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-------class VideoClip(Clip):-- """-- Base class for video clips. See ``MovieClip``, ``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 if ismask else- # VideoClip(ismask=True).set_get_frame(lambda t:None))- 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]-- @requires_duration- def preview(self, fps=15, audio=True, audiofps=22050):- """- 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.-- """-- if self.ismask:- self = self.to_RGB()-- screen = pg.display.set_mode(self.size)-- if (audio == True) and (self.audio != None):- self.audio.preview(fps=audiofps, sleep=False)-- img = self.get_frame(0)- for t in np.arange(0, self.duration, 1.0 / fps):- t1 = time.time()- imdisplay(img, screen)- img = self.get_frame(t)- t2 = time.time()- time.sleep(max(0, 1.0 / fps - (t2 - t1)))-- def show(self, 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 self.ismask:- self = self.to_RGB()- if with_mask and (self.mask != None):- self = CompositeVideoClip(self.size, [self])- imdisplay(self.get_frame(t))-- 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')-- cv2.imwrite(filename,im)-- def with_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(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)-- @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_movie(self, filename, fps=24, codec='DIVX',- audio=True, audiofps=44100, temp_wav='temp.wav',- remove_temp = 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_movie)-- 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- - 'raw' : will produce a raw video, of perfect quality, but- possibly very huge size.- - 'DIVX' : For nice quality, very well compressed videos.- - 'XVID' : A little better than 'DVIX', a little heavier.- - Any of the (many) other codec supported by OpenCV, written- as a string of four characters. See here for a list:- http://remisoft.ath.cx/article14/fourcc-- :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.-- """-- print "Making file %s ..."%filename-- if codec == 'raw':- codec = 0- else:- codec = FOURCC(*codec)----- # Prepare audio-- if isinstance(audio, str): # audio is a file- temp_wav = audio- elif self.audio is None: # if audio not a file and no clip.audio- audio = False- elif audio: # audio=True and clip.audio exists.- print "Rendering audio.",- self.audio.to_soundfile(temp_wav, audiofps)-- # If there is any audio we will need to first write a mute- # temporary video file-- if audio:- name, ext = os.path.splitext(filename)- videofile = name + 'TEMP' + ext- else:- videofile = filename-- # Write the movie- print "Rendering video :",-- writer = cv2.VideoWriter(videofile, codec, fps, self.size)- tt = np.arange(0, self.duration, 1.0/fps)- lentt = len(tt)- for i,t in enumerate(tt):- writer.write(self.get_frame(t)[:,:,::-1].astype('uint8'))- if i % (len(tt)/10) == 0:- print "%d"%(100 * i / len(tt)) + "% ",- try:- writer.release() # some versions of opencv don't have that one- except:- pass- print "done !"-- # Merge with audio if any and trash temporary files.-- if audio:- print "Now merging video and audio...",- ffmpeg.merge_video_audio(videofile,temp_wav,filename)- if remove_temp:- os.remove(videofile)- if not isinstance(audio,str):- os.remove(temp_wav)- print "done !"--- def blit_on(self, picture, t):- """ Returns the result of the blit of the clip's frame at time `t`- on the given `picture` """-- 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- mask = (None if (self.mask is None) else self.mask.get_frame(ct))-- # Set position- pos = list(self.pos(ct))- img = self.get_frame(ct)-- hi, wi = img.shape[:2]-- # see set_pos doc for details- 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 subapply(self, fun, ta=0, tb=None):- """- 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 = fun(self.subclip(ta, tb))- 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)-- @apply_to_mask- def resize(self, 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.-- :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.--- """- w, h = self.size-- if newsize != None:- if isinstance(newsize, (int, float)):- newsize = [newsize * w, newsize * h]- elif height != None:- newsize = [w * height / h, height]- elif width != None:- newsize = [width, h * width / w]-- newsize = map(int, newsize)[::-1]-- if self.ismask:- fl = lambda pic: 1.0*cv2.resize((255 * pic).astype('uint8'),- tuple(newsize[::-1]), interpolation=cv2.INTER_AREA)/255- else:- fl = lambda pic: cv2.resize(pic.astype('uint8'),- tuple(newsize[::-1]), interpolation=cv2.INTER_AREA)-- return self.fl_image(fl)-- 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 bigger size.-- :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 = self.size- if pos is None:- pos = ('center', 'center')- colorclip = ColorClip(size, color)- if col_opacity:- colorclip = colorclip.with_mask().set_opacity(col_opacity)-- return CompositeVideoClip(size, [colorclip, self.set_pos(pos)],- transparent=(col_opacity != None))-- @apply_to_mask- def margin(self, 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 (self.mask is None) and not (self.ismask):- self = self.with_mask()-- if mar != None:- left = right = top = bottom = mar-- new_w, new_h = self.w + left + right, self.h + top + bottom-- if self.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 + self.h, left:left + self.w] = pic- return im-- return self.fl_image(fl)-- def padded(self, size, color=(0, 0, 0)):- """ internal margin by shrinking the frame """- w, h = self.size- return self.resize((x - 2 * size, y - 2 * size)).margin(size, color)-- def crop(self, x1=0, y1=0, x2=None, y2=None):- if x2 is None:- x2 = self.size[0]- if y2 is None:- y2 = self.size[1]- return self.fl_image(lambda pic: pic[y1:y2, x1:x2],- applyto=['mask'])-- #--------------------------------------------------------------- # C O M P O S I T I N G- 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):- """ mask must be a greyscale (0-1) Clip"""- newclip = copy(self)- newclip.audio = audioclip- return newclip-- def set_mask(self, mask):- """ mask must be a greyscale (0-1) Clip"""- newclip = copy(self)- newclip.mask = mask- return newclip-- def set_opacity(self, op):- """op is any float (normaly between 0 and 1) by which the- clip's mask will be multiplied """- 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-- def fadein(self, duration):- """- Makes the clip appear progressively, over ``duration`` seconds.- Only works when the clip is include in a CompositeVideoClip.- """- newclip = copy(self)- fading = lambda t: min(1.0 * t / duration, 1)- fl = lambda gf, t: fading(t) * gf(t)- newclip.mask = self.mask.fl(fl)- return newclip-- @requires_duration- def fadeout(self, duration):- """- Makes the clip disappear progressively, over ``duration`` seconds.- Only works when the clip is include in a CompositeVideoClip.- """- newclip = copy(self)- fading = lambda t: min(1.0 * (self.duration - t) / duration, 1)- fl = lambda gf, t: fading(t) * gf(t)- newclip.mask = self.mask.fl(fl)- return newclip-- #--------------------------------------------------------------- # CONVERSIONS- def to_ImageClip(self):- """ Return an ImageClip made out of the clip's first frame """- return ImageClip(self.get_frame(0))-- 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('int'))- newclip.ismask = False- return newclip- else:- return self-- #----------------------------------------------------------------- # Miscellaneous- def manual_tracking(self, t1=None, t2=None, fps=5):- """- Allows manual tracking of an object in the video clip between- times `t1` and `t2`. This displays the clip frame by frame- and you must click on the object 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... ]-- >>> 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)-- """-- screen = pg.display.set_mode(self.size)- step = 1.0 / fps- if (t1 is None) and (t2 is None):- t1,t2 = 0, self.duration- elif (t2 is None):- t2 = t1 + step / 2- t = t1- txyList = []-- while t < t2:-- imdisplay(self.get_frame(t), screen)- doContinue = True-- while doContinue:-- for event in pg.event.get():-- if event.type == pg.KEYDOWN:- if (event.key == pg.K_BACKSLASH):- t -= step- txyList.pop()- doContinue = False-- elif event.type == pg.MOUSEBUTTONDOWN:- x, y = pg.mouse.get_pos()- txyList.append((t, x, y))- doContinue = False- t += step-- return txyList---class MovieClip(VideoClip):-- """-- A video clip originating from a movie file. For instance:-- >>> clip = MovieClip("myHolidays.mp4")- >>> clip2 = MovieClip("myMaskVideo.avi",ismask = True)-- :param source: Any video file: .ogv, .mp4, .mpeg, .avi, .mov etc.- :param ismask: `True` if the clip is a mask.- :param audio: If `True`, then the audio is extracted from the video- file, in wav format, and it attributed to the clip.-- :ivar source: Name of the original video file- :ivar fps: Frames per second in the original file.- :ivar nframes: Total number of frames in the original file.-- """-- def __init__(self, source, ismask=False, audio=False):-- VideoClip.__init__(self, ismask)-- self.cap = cv2.VideoCapture(source)-- self.source = source-- self.fps = self.cap.get(CAP_PROP_FPS)-- self.nframes = self.cap.get(CAP_PROP_FRAME_COUNT)-- duration = 1.0 * (self.nframes) / self.fps- self.duration = duration-- self.size = self.cap.read()[1].shape[:2][::-1]- self.last_frame_read = 0-- def get_frame(t):- """- Gets the frame of the video at time t. Note for coders:- getting an arbitrary frame in the video with opencv can be- painfully slow if some decoding has to be made. This- function tries to avoid fectching arbitrary frames whenever- possible, by moving between adjacent frames.- """-- nframe = int(self.fps * t)-- if nframe == self.last_frame_read:- return self.cap.retrieve()[1][:, :, ::-1]- elif (self.last_frame_read < nframe < (self.last_frame_read + 5)):- for i in range(nframe - self.last_frame_read - 1):- self.cap.read()-- else:- self.cap.set(CAP_PROP_POS_FRAMES, nframe - 1)-- frame = self.cap.read()[1]- if frame is None:- return self.last_frame- else:- self.last_frame_read = nframe- frame = frame[:, :, ::-1]- self.last_frame = frame- return frame-- self.get_frame = get_frame-- if audio:- temp = 'temp.wav'- try:- ffmpeg.extract_audio(source, temp)- self.audio = SoundClip(temp)- os.remove(temp)- except:- print "No audio detected in %s."%source---class DirectoryClip(VideoClip):-- """-- A VideoClip from a directory containing pictures-- """-- def __init__(self, source, fps, transparent=True, repeat=False, ismask=False):-- VideoClip.__init__(self, ismask=ismask)-- self.directory = source- self.fps = fps- self.pics = sorted(["%s/%s" % (source, f) for f in os.listdir(source)- if not f.endswith('.txt')])-- 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(source, 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_movie(self, filename, bitrate=3000, audio=None):- """- 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:- name, ext = os.path.splitext(filename)- videofile = name + 'TEMP' + ext- else:- videofile = filename-- cmd = ("ffmpeg -y -f image2 -r %d -i %s/%s" % (- self.fps, self.directory, self.directory) + "%06d.png" +- " -b %dk -r %d %s" % (bitrate, self.fps, videofile))-- print "\nrunning: %s" % cmd- os.system(cmd)-- if audio != None:- cmd = (" ffmpeg -y -i %s" % audio +- " -i %s -strict experimental %s" % (videofile, filename))- print "running: %s" % cmd- os.system(cmd)- os.remove(videofile)--class ImageClip(VideoClip):-- """-- A video clip originating from a picture. For instance:-- >>> clip = ImageClip("myHouse.jpeg")- >>> clip = ImageClip( someNumpyArray )-- :param img: Any picture file (png, tif, jpeg, etc.) or any array- representing an 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):-- VideoClip.__init__(self, ismask=ismask)-- if isinstance(img, str):- img = imread(img)-- if len(img.shape) == 3:- 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-- self.img = img- self.size = img.shape[:2][::-1]- self.get_frame = lambda t: self.img---class ColorClip(VideoClip):-- """-- To be written-- """-- def __init__(self, size, col=(0, 0, 0), ismask=False):- VideoClip.__init__(self, ismask=ismask)- self.size = size- w, h = size- shape = (h, w) if isinstance(col, (int, float)) else (h, w, len(col))- self.img = np.tile(col, w * h).reshape(shape)- self.get_frame = lambda t: self.img---class TextClip(ImageClip):-- """-- A VideoClip 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) it will be- wrapped automatically (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-- :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'-- 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 transparent "- + "-fill %s " % (color)- + "-font %s " % font- + ("" if (fontsize is None)- else "-pointsize %d " % fontsize)- + ("" if (kerning is None)- else "-kerning %0.1f" % kerning)- + ("" if (stroke_color is None)- else "-stroke %s -strokewidth %d " % (- stroke_color, stroke_width))- + ("" if (size is None)- else "-size %sx%s " % (size[0], size[1]))- + "-gravity %s " % align- + ("" if (interline is None)- else "-interline-spacing %d " % interline)- + "%s:'%s' " % (method, txt)- + tempfile)-- if print_cmd:- print cmd-- os.system(cmd)- 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', 'font'],- 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:]]---class CompositeVideoClip(VideoClip):-- """-- A VideoClip made of other videoclips displayed together.-- :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, size, clips, bg_color=None, transparent=False,- ismask=False):-- VideoClip.__init__(self)- self.size = size- self.ismask = ismask- self.clips = clips- self.transparent = transparent- if bg_color is None:- bg_color = 0.0 if self.ismask else (0, 0, 0)- 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(self.size, maskclips,- 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 concat(cliplist, transition=None, bg_color=(0, 0, 0), transparent=False,- ismask=False):- """-- Makes one video clip by concatenating several clips of a list.- (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``.-- :param cliplist: a list of video clips which must all have- their ``duration`` attributes set.- :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.- :param transition: a clip that will be played between each two- clips of the list.-- """-- if transition:- l = [[v, transition] for v in cliplist[:-1]]- cliplist = reduce(lambda x, y: x + y, l) + [cliplist[-1]]-- sizes = [v.size for v in cliplist]- tt = np.cumsum([0] + [c.duration for c in cliplist])-- if len(set(sizes)) == 1: # All clips have the same size- result = VideoClip()- result.size = cliplist[0].size- result.cliplist = cliplist- result.tt = tt- result.duration = tt[-1]-- def gf(t):- i = max([i for i, e in enumerate(tt) if e <= t])- return result.cliplist[i].get_frame(t - tt[i])- result.get_frame = gf-- else:-- w = max([r[0] for r in sizes])- h = max([r[1] for r in sizes])- result = CompositeVideoClip((w, h),- [c.set_start(t).set_pos(('center', 'center'))- for (c, t) in zip(cliplist, tt)],- bg_color=bg_color,- ismask=ismask, transparent=transparent)-- # Compute the mask if any-- if transparent and (not ismask):- result.mask = concat([c.mask for c in cliplist], transparent=False,- ismask=True)--- # Compute the audio if any-- audios = [c.audio for c in cliplist if c.audio!=None]- if len(audios)>1:- result.audio = CompositeAudioClip([a.set_start(t)- for a,t in zip(audios,tt)])-- return resultdiff --git a/moviepy/__init__.py b/moviepy/__init__.pyindex 6d764d1b..043f7792 100644--- a/moviepy/__init__.py+++ b/moviepy/__init__.py@@ -1,4 +1,20 @@-#__all__ = ['Clip','VideoClip','AudioClip']-from Clip import *-from VideoClip import *-from AudioClip import *+from video.io.VideoFileClip import VideoFileClip+from video.ImageClip import ImageClip, ColorClip, TextClip+from video.compositing.CompositeVideoClip import CompositeVideoClip+from video.compositing.concatenate import concatenate+from audio.io.AudioFileClip import AudioFileClip+from tools import cvsecs++import video.fx as vfx+import video.compositing.transitions as transfx+import audio.fx as afx+import video.io.ffmpeg as ffmpeg+++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/ffmpeg.py b/moviepy/ffmpeg.pydeleted file mode 100644index b3689d0d..00000000--- a/moviepy/ffmpeg.py+++ /dev/null@@ -1,80 +0,0 @@-""" Very experimental 'bindings' to ffmpeg and ImageMagick."""--import os--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"- cmd = ("ffmpeg -y -f image2 -r %d -i %s/%s" % (fps, folder, folder) +- s + " -b %dk -r %d %s" % (bitrate, self.fps, filename))- os.system(cmd)- return cmd---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)-- cmd = ( "ffmpeg -y -ss %0.2f -t %0.2f"%(t1, t2-t1)+- " -i %s -vcodec copy -acodec copy %s"%(filename, targetname))- os.system(cmd)- return cmd----def merge_video_audio(video,audio,output):- """ merges video file ``video`` and audio file ``audio`` into one- movie file ``output``. """- cmd = "ffmpeg -y -i %s -i %s -vcodec copy -acodec libvorbis %s"%(- audio, video, output)- print "running: %s" % cmd- os.system(cmd)- return cmd--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-- cmd = "convert -coalesce %s %s" %(- gif_file, os.path.join(dirName,"%04d.png"))- os.system(cmd)- return dirName---def extract_audio(inputfile,output,bitrate=3000,fps=44100):- """ extract the sound from a video file and save it in ``output`` """- cmd = "ffmpeg -y -i %s -ab %dk -ar %d %s"%(inputfile,bitrate,fps,output)- os.system(cmd)- return cmd---def resize(video,output,size):- """ resizes ``video`` to new size ``size`` and write the result- in file ``output``. """- cmd = "ffmpeg -i %s -vf scale=%d:%d %s"%(video,res[0],res[1],output)- os.system(cmd)- return cmd