Video editing with Python
replaced freeze_at... by freeze, added detec_scenes to video.cuts, replaced mask_inv by invert_colors.
Zulkob358181a1e1c
diff --git a/README.rst b/README.rstindex 9dfc083f..596d8689 100644--- a/README.rst+++ b/README.rst@@ -1,7 +1,7 @@MoviePy========-MoviePy (full documentation here_) is a Python module for video editing. It enables basic operations (cuts, concatenations, title insertions) to be done in a few lines, and can be used for video compositing (a.k.a. non-linear editing), video processing, or to create advanced effects. It can read and write all the most common video formats, including GIF.+MoviePy (full documentation here_) is a Python module for video editing: cuts, concatenations, title insertions, video compositing (a.k.a. non-linear editing), video processing, and creation of custom effects. See the gallery_ for some examples of use.A typical MoviePy script looks like this: ::@@ -10,27 +10,29 @@ A typical MoviePy script looks like this: ::# Load myHolidays.mp4 and select the subclip 00:00:50 - 00:00:60clip = 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').set_duration(10)+ # Generate a 10-second centered text clip (many options available ! )+ txt_clip = ( TextClip("My Holidays 2013",fontsize=70,color='white')+ .set_position('center')+ .set_duration(10) )# Overlay the text clip above the first clipfinal_clip = CompositeVideoClip([clip, txt_clip])# write the result to a file in any format- final_clip.to_videofile("myHolidays_edited.avi",fps=25, codec='mpeg4')+ final_clip.to_videofile("myHolidays_edited.webm",fps=25)-See the gallery_ (in construction) for more.+MoviePy can read and write all the most common audio and video formats, including GIF, and runs on Windows/Mac/Linux, with Python 2 and 3.++Contribute !+-------------MoviePy is an open-source software originally written by Zulko_ and released under the MIT licence. The project is hosted on Github_ , where everyone is welcome to contribute, ask for help or simply give feedback.-You can also discuss Moviepy on Reddit_ or on the mailing list [email protected] .+You can also discuss about the project on Reddit_ or on the mailing list [email protected] .Installation---------------MoviePy works on Windows, Linux and Mac OS, with Python 2 and 3. If you have trouble installing it on your computer, please provide feedback !-**Method with pip:** if you have ``pip`` installed, just type this in a terminal (sudo is optional on some systems) ::(sudo) pip install moviepy@@ -45,6 +47,7 @@ This method may fail if ``ez_setup`` is not installed on your computer. In thisMoviePy depends on the Python modules Numpy_, Decorator_, and tqdm_, which will be automatically installed during MoviePy's installation.+This should work on Windows/Mac/Linux, with Python 2 and 3 ; if you have trouble installing MoviePy or one of its dependencies, please provide feedback !Linking to ffmpeg~~~~~~~~~~~~~~~~~~diff --git a/docs/getting_started/quick_presentation.rst b/docs/getting_started/quick_presentation.rstindex a280bb3c..f315c5a9 100644--- a/docs/getting_started/quick_presentation.rst+++ b/docs/getting_started/quick_presentation.rst@@ -51,8 +51,8 @@ In a typical MoviePy script, you load video or audio files, modify them, put the# Overlay the text clip on the first video clipvideo = CompositeVideoClip([clip, txt_clip])- # Write the result to a file- video.write_videofile("myHolidays_edited.avi",fps=24, codec='mpeg4')+ # Write the result to a file (many options available !)+ video.write_videofile("myHolidays_edited.webm")How MoviePy worksdiff --git a/docs/ref/videofx/moviepy.video.fx.all.time_symmetrize.rst b/docs/ref/videofx/moviepy.video.fx.all.time_symmetrize.rstnew file mode 100644index 00000000..4f109d50--- /dev/null+++ b/docs/ref/videofx/moviepy.video.fx.all.time_symmetrize.rst@@ -0,0 +1,6 @@+moviepy.video.fx.all.time_symmetrize+====================================++.. currentmodule:: moviepy.video.fx.all++.. autofunction:: time_symmetrize\ No newline at end of filediff --git a/moviepy/audio/tools/__init__.py b/moviepy/audio/tools/__init__.pynew file mode 100644index 00000000..d51a08cc--- /dev/null+++ b/moviepy/audio/tools/__init__.py@@ -0,0 +1,3 @@+"""+Tools to better process/edit/cut audio.+"""diff --git a/moviepy/audio/tools/cuts.py b/moviepy/audio/tools/cuts.pynew file mode 100644index 00000000..eddd0777--- /dev/null+++ b/moviepy/audio/tools/cuts.py@@ -0,0 +1,20 @@++import numpy as np+def find_audio_period(aclip, t_min=.1, t_max=2, t_res=.01):+ """ Finds the period, in seconds of an audioclip.++ The beat is then given by bpm = 60/T++ t_min and _tmax are bounds for the returned value, t_res+ is the numerical precision+ """+ chunksize = int(t_res*aclip.fps)+ chunk_duration = 1.0*chunksize/aclip.fps+ # v denotes the list of volumes+ v = np.array([(c**2).sum() for c in+ aclip.iter_chunks(chunksize)])+ v = v-v.mean()+ corrs = np.correlate(v, v, mode = 'full')[-len(v):]+ corrs[:int(t_min/chunk_duration)]=0+ corrs[int(t_max/chunk_duration):]=0+ return chunk_duration*np.argmax(corrs)\ No newline at end of filediff --git a/moviepy/editor.py b/moviepy/editor.pyindex 9260d73a..b33c3e65 100644--- a/moviepy/editor.py+++ b/moviepy/editor.py@@ -58,14 +58,15 @@ for method in ["vfx.crop","vfx.fadein","vfx.fadeout",+ "vfx.invert_colors","vfx.loop","vfx.margin","vfx.mask_and",- "vfx.mask_inv","vfx.mask_or","vfx.resize","vfx.speedx"]:+exec("VideoClip.%s = %s"%( method.split('.')[1], method))@@ -74,6 +75,7 @@ for method in ["afx.audio_fadein","afx.audio_loop","afx.volumex"]:+exec("AudioClip.%s = %s"%( method.split('.')[1], method))diff --git a/moviepy/video/fx/blackwhite.py b/moviepy/video/fx/blackwhite.pyindex d9489371..5d4f1239 100644--- a/moviepy/video/fx/blackwhite.py+++ b/moviepy/video/fx/blackwhite.py@@ -13,7 +13,7 @@ def blackwhite(clip, RGB = [1,1,1], preserve_luminosity=True):R,G,B = 1.0*np.array(RGB)/ (sum(RGB) if preserve_luminosity else 1)def fl(im):- im = (R*im[:,:,0] + G*im[:,:,1] + B*im[:,:,2])/3+ im = (R*im[:,:,0] + G*im[:,:,1] + B*im[:,:,2])return np.dstack(3*[im]).astype('uint8')return clip.fl_image(fl)diff --git a/moviepy/video/fx/freeze.py b/moviepy/video/fx/freeze.pynew file mode 100644index 00000000..ffbf3a00--- /dev/null+++ b/moviepy/video/fx/freeze.py@@ -0,0 +1,26 @@+from moviepy.decorators import requires_duration+from moviepy.video.VideoClip import ImageClip+from moviepy.video.compositing.concatenate import concatenate_videoclips++@requires_duration+def freeze(clip, t=0, freeze_duration=None, total_duration=None,+ padding_end=0):+ """ Momentarily freeze the clip at time t.++ Set `t='end'` to freeze the clip at its end.+ With ``duration``you can specify the duration of the freeze.+ With ``total_duration`` you can specify the total duration of+ the clip and the freeze (i.e. the duration of the freeze is+ automatically calculated). One of them must be provided.+ """++ if t=='end':+ t = clip.duration++ if freeze_duration is None:+ freeze_duration = total_duration - clip.duration++ before = [clip.subclip(0,t)] if (t!=0) else []+ freeze = [clip.to_ImageClip(t).set_duration(freeze_duration)]+ after = [clip.subclip(t)] if (t !=clip.duration) else []+ return concatenate_videoclips(before+freeze+after)\ No newline at end of filediff --git a/moviepy/video/fx/freeze_at_end.py b/moviepy/video/fx/freeze_at_end.pydeleted file mode 100644index 89f9f8ac..00000000--- a/moviepy/video/fx/freeze_at_end.py+++ /dev/null@@ -1,25 +0,0 @@-from moviepy.decorators import requires_duration-from moviepy.video.VideoClip import ImageClip-from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip---@requires_duration-def freeze_at_end(clip, freeze_duration=None,- total_duration=None, delta=0.05):- """- Makes the clip freeze on its last frame. With ``duration`` you can- specify the duration of the freeze. With ``total_duration`` you can- specify the total duration of the clip and the freeze (i.e. the- duration of the freeze is automatically calculated). If neither- is provided, the freeze will have an infinite length.-- The clip is frozen on the frame at time (clip.duration - delta)- """-- freezed_clip = ImageClip(clip.get_frame(clip.end - delta))- if total_duration:- freeze_duration = total_duration - clip.duration- if freeze_duration:- freezed_clip = freezed_clip.set_duration(freeze_duration)-- return CompositeVideoClip([clip,freezed_clip.set_start(clip.end)])diff --git a/moviepy/video/fx/freeze_at_start.py b/moviepy/video/fx/freeze_at_start.pydeleted file mode 100644index c27ccfb2..00000000--- a/moviepy/video/fx/freeze_at_start.py+++ /dev/null@@ -1,25 +0,0 @@-from moviepy.decorators import requires_duration-from moviepy.video.VideoClip import ImageClip-from moviepy.video.compositing.concatenate import concatenate_videoclips--@requires_duration-def freeze_at_start(clip, freeze_duration=None, total_duration=None):- """ Momentarily freeze the clip on its first frame.-- With ``duration``you can specify the duration of the freeze.- With ``total_duration`` you can specify the total duration of- the clip and the freeze (i.e. the duration of the freeze is- automatically calculated). If neither is provided, the freeze- will have an infinite length.- """-- freezed_clip = ImageClip(clip.get_frame(0))- if clip.mask:- freezed_clip.mask = ImageClip(clip.mask.get_frame(0))-- if total_duration:- freeze_duration = total_duration - clip.duration- if freeze_duration:- freezed_clip = freezed_clip.set_duration(freeze_duration)-- return concatenate_videoclips([freezed_clip, clip])diff --git a/moviepy/video/fx/invert_colors.py b/moviepy/video/fx/invert_colors.pynew file mode 100644index 00000000..0fb948eb--- /dev/null+++ b/moviepy/video/fx/invert_colors.py@@ -0,0 +1,8 @@+def invert_colors(clip):+ """ Returns the color-inversed clip.++ The values of all pixels are replaced with (255-v) or (1-v) for masks+ Black becomes white, green becomes purple, etc.+ """+ maxi = (1.0 if clip.ismask else 255)+ return clip.fl_image(lambda f : maxi - f)diff --git a/moviepy/video/fx/mask_inv.py b/moviepy/video/fx/mask_inv.pydeleted file mode 100644index c74fb0de..00000000--- a/moviepy/video/fx/mask_inv.py+++ /dev/null@@ -1,3 +0,0 @@-def mask_inv(clip):- """ Returns the color-inversed mask."""- return clip.fl_image(lambda f : 1.0 - f)\ No newline at end of filediff --git a/moviepy/video/tools/cuts.py b/moviepy/video/tools/cuts.pyindex d364fa71..37cd92b1 100644--- a/moviepy/video/tools/cuts.py+++ b/moviepy/video/tools/cuts.py@@ -5,10 +5,79 @@ import numpy as npdef find_video_period(clip,fps=None,tmin=.3):+ """ Finds the period of a video based on frames correlation """if fps is None:fps=clip.fpsframe = lambda t: clip.get_frame(t).flatten()tt = np.arange(tmin,clip.duration,1.0/ fps)[1:]ref = frame(0)corrs = [ np.corrcoef(ref, frame(t))[0,1] for t in tt]- return tt[np.argmax(corrs)]\ No newline at end of file+ return tt[np.argmax(corrs)]++++def detect_scenes(clip=None, luminosities=None, thr=10,+ progress_bar=False, fps=None):++ """ Detects scenes of a clip based on luminosity changes.++ Note that for large clip this may take some time++ Returns+ --------+ cuts, luminosities+ cuts is a series of cuts [(0,t1), (t1,t2),...(...,tf)]+ luminosities are the luminosities computed for each+ frame of the clip.++ Parameters+ -----------++ clip+ A video clip. Can be None if a list of luminosities is+ provided instead. If provided, the luminosity of each+ frame of the clip will be computed. If the clip has no+ 'fps' attribute, you must provide it.++ luminosities+ A list of luminosities, e.g. returned by detect_scenes+ in a previous run.++ thr+ Determines a threshold above which the 'luminosity jumps'+ will be considered as scene changes. A scene change is defined+ as a change between 2 consecutive frames that is larger than+ (avg * thr) where avg is the average of the absolute changes+ between consecutive frames.++ progress_bar+ We all love progress bars ! Here is one for you, in option.++ fps+ Must be provided if you provide no clip or a clip without+ fps attribute.+++++ """++ if fps is None:+ fps = clip.fps++ if luminosities is None:+ luminosities = [f.sum() for f in clip.iter_frames(+ fps=fps, dtype='uint32', progress_bar=1)]++ luminosities = np.array(luminosities, dtype=float)+ if clip is not None:+ end = clip.duration+ else:+ end = len(luminosities)*(1.0/fps)+ lum_diffs = abs(np.diff(luminosities))+ avg = lum_diffs.mean()+ luminosity_jumps = 1+np.array(np.nonzero(lum_diffs> thr*avg))[0]+ tt = [0]+list((1.0/fps) *luminosity_jumps) + [end]+ #print tt+ cuts = [(t1,t2) for t1,t2 in zip(tt,tt[1:])]+ return cuts, luminositiesdiff --git a/setup.py b/setup.pyindex 5b329894..d85b97e4 100644--- a/setup.py+++ b/setup.py@@ -10,9 +10,9 @@ from setuptools import setup, find_packagessetup(name='moviepy',version=__version__,author='Zulko 2014',- description='Module for script-based video editing',+ description='Video editing with Python',long_description=open('README.rst').read(),license='see LICENSE.txt',- keywords="movie editing film mixing script-based",+ keywords="video editing audio compositing numpy ffmpeg ",packages= find_packages(exclude='docs'),install_requires= ['numpy', 'decorator', 'tqdm'])