Skip to content

Video editing with Python

replace time_can_be_tuple by convert_to_time (more general). Improved docstrings, fixed bug in fx.all.

Zulkoe80b6194bea2
diff --git a/examples/star_worms.py b/examples/star_worms.py
index d58468e0..a5ea88d7 100644
--- a/examples/star_worms.py
+++ b/examples/star_worms.py
@@ -94,7 +94,8 @@ stars_darkened = stars.fl_image(lambda pic: (0.6*pic).astype('int16'))
# COMPOSE THE MOVIE
final = CompositeVideoClip([
- stars, warped_txt.set_pos(('center','bottom'))],
+ stars_darkened,
+ warped_txt.set_pos(('center','bottom'))],
size = moviesize)
diff --git a/moviepy/Clip.py b/moviepy/Clip.py
index 545c4e0f..ca8323fd 100644
--- a/moviepy/Clip.py
+++ b/moviepy/Clip.py
@@ -9,9 +9,9 @@ import numpy as np
from moviepy.decorators import ( apply_to_mask,
apply_to_audio,
- time_can_be_tuple,
requires_duration,
- outplace)
+ outplace,
+ convert_to_seconds)
from tqdm import tqdm
class Clip:
@@ -196,12 +196,14 @@ class Clip:
@apply_to_mask
@apply_to_audio
- @time_can_be_tuple
+ @convert_to_seconds(['t'])
@outplace
def set_start(self, t, change_end=True):
"""
Returns a copy of the clip, with the ``start`` attribute set
- to ``t`` (in seconds).
+ to ``t``, which can be expressed in seconds (15.35), in (min, sec),
+ in (hour, min, sec), or as a string: '01:03:05.35'.
+
If ``change_end=True`` and the clip has a ``duration`` attribute,
the ``end`` atrribute of the clip will be updated to
@@ -225,12 +227,14 @@ class Clip:
@apply_to_mask
@apply_to_audio
- @time_can_be_tuple
+ @convert_to_seconds(['t'])
@outplace
def set_end(self, t):
"""
Returns a copy of the clip, with the ``end`` attribute set to
- ``t``. Also sets the duration of the mask and audio, if any,
+ ``t``, which can be expressed in seconds (15.35), in (min, sec),
+ in (hour, min, sec), or as a string: '01:03:05.35'.
+ Also sets the duration of the mask and audio, if any,
of the returned clip.
"""
self.end = t
@@ -244,12 +248,13 @@ class Clip:
@apply_to_mask
@apply_to_audio
- @time_can_be_tuple
+ @convert_to_seconds(['t'])
@outplace
def set_duration(self, t, change_end=True):
"""
Returns a copy of the clip, with the ``duration`` attribute
- set to ``t``.
+ set to ``t``, which can be expressed in seconds (15.35), in (min, sec),
+ in (hour, min, sec), or as a string: '01:03:05.35'.
Also sets the duration of the mask and audio, if any, of the
returned clip.
If change_end is False, the start attribute of the clip will
@@ -276,12 +281,13 @@ class Clip:
- @time_can_be_tuple
+ @convert_to_seconds(['t'])
def is_playing(self, t):
"""
- If t is a number, returns true if t is between the start and
- the end of the clip.
+ If t is a time, returns true if t is between the start and
+ the end of the clip. t can be expressed in seconds (15.35),
+ in (min, sec), in (hour, min, sec), or as a string: '01:03:05.35'.
If t is a numpy array, returns False if none of the t is in
theclip, else returns a vector [b_1, b_2, b_3...] where b_i
is true iff tti is in the clip.
@@ -308,13 +314,15 @@ class Clip:
return( (t >= self.start) and
((self.end is None) or (t < self.end) ) )
- @time_can_be_tuple
+ @convert_to_seconds(['t_start', 't_end'])
@apply_to_mask
@apply_to_audio
def subclip(self, t_start=0, t_end=None):
"""
Returns a clip playing the content of the current clip
- between times ``t_start`` and ``t_end`` (in seconds).
+ between times ``t_start`` and ``t_end``, which can be expressed
+ in seconds (15.35), in (min, sec), in (hour, min, sec), or as a
+ string: '01:03:05.35'.
If ``t_end`` is not provided, it is assumed to be the duration
of the clip (potentially infinite).
If ``t_end`` is a negative value, it is reset to
@@ -355,11 +363,13 @@ class Clip:
@apply_to_mask
@apply_to_audio
- @time_can_be_tuple
+ @convert_to_seconds(['ta', 'tb'])
def cutout(self, ta, tb):
"""
Returns a clip playing the content of the current clip but
- skips the extract between ``ta`` and ``tb`` (in seconds).
+ skips the extract between ``ta`` and ``tb``, which can be
+ expressed in seconds (15.35), in (min, sec), in (hour, min, sec),
+ or as a string: '01:03:05.35'.
If the original clip has a ``duration`` attribute set,
the duration of the returned clip is automatically computed as
`` duration - (tb - ta)``.
@@ -414,6 +424,4 @@ class Clip:
nframes = int(self.duration*fps)+1
return tqdm(generator(), total=nframes)
- return generator()
-
-
+ return generator()
\ No newline at end of file
diff --git a/moviepy/decorators.py b/moviepy/decorators.py
index 93522c48..ccd48b76 100644
--- a/moviepy/decorators.py
+++ b/moviepy/decorators.py
@@ -37,17 +37,6 @@ def apply_to_audio(f, clip, *a, **k):
if hasattr(newclip, 'audio') and (newclip.audio != None):
newclip.audio = f(newclip.audio, *a, **k)
return newclip
-
-
-
-def add_mask_if_none(f, clip, *a, **k):
- """ Add a mask to the clip if there is none. """
-
- if clip.mask is None:
- clip = clip.add_mask()
- return f(clip, *a, **k)
-
@decorator.decorator
@@ -78,16 +67,27 @@ def audio_video_fx(f, clip, *a, **k):
else:
return f(clip, *a, **k)
+def preprocess_args(fun,varnames):
+
+ def warper(f, *a, **kw):
+ names = f.func_code.co_varnames
+ new_a = [cvsecs(arg) if (name in varnames) else arg
+ for (arg, name) in zip(a, names)]
+ new_kw = {k: fun(v) if k in varnames else v
+ for (k,v) in kw.items()}
+ return f(*new_a, **new_kw)
+ return decorator.decorator(warper)
+
+
+def convert_to_seconds(varnames):
+ "Converts the specified variables to seconds"
+ return preprocess_args(cvsecs, varnames)
+
@decorator.decorator
-def time_can_be_tuple(f, clip, *a, **k):
- """
- All tuples in the arguments of f will be considered as time and
- converted to seconds.
- """
-
- fun = lambda e: e if (not isinstance(e,tuple)) else cvsecs(*e)
- a = map(fun,a)
- k = dict( [(m, fun(n)) for m,n in k.items()])
- return f(clip, *a, **k)
+def add_mask_if_none(f, clip, *a, **k):
+ """ Add a mask to the clip if there is none. """
+ if clip.mask is None:
+ clip = clip.add_mask()
+ return f(clip, *a, **k)
\ No newline at end of file
diff --git a/moviepy/tools.py b/moviepy/tools.py
index 7278c38c..b2dd1efd 100644
--- a/moviepy/tools.py
+++ b/moviepy/tools.py
@@ -5,7 +5,7 @@ Misc. useful functions that can be used at many places in the program.
import subprocess as sp
import sys
import warnings
-
+import re
def sys_write_flush(s):
""" Writes and flushes without delay a text in the console """
@@ -38,21 +38,38 @@ def subprocess_call(cmd, verbose=True, errorprint=True):
del proc
-def cvsecs(*args):
- """
- Converts a time to second. Either cvsecs(min,secs) or
- cvsecs(hours,mins,secs).
- >>> cvsecs(5.5) # -> 5.5 seconds
- >>> cvsecs(10, 4.5) # -> 604.5 seconds
- >>> cvsecs(1, 0, 5) # -> 3605 seconds
+def cvsecs(time):
+ """ Will convert any time into seconds.
+ Here are the accepted formats:
+
+ >>> cvsecs(15.4) -> 15.4 # seconds
+ >>> cvsecs( (1,21.5) ) -> 81.5 # (min,sec)
+ >>> cvsecs( (1,1,2) ) -> 3662 # (hr, min, sec)
+ >>> cvsecs('01:01:33.5') -> 3693.5 #(hr,min,sec)
+ >>> cvsecs('01:01:33.045') -> 3693.045
+ >>> cvsecs('01:01:33,5') #coma works too
"""
- if len(args) == 1:
- return args[0]
- elif len(args) == 2:
- return 60*args[0]+args[1]
- elif len(args) ==3:
- return 3600*args[0]+60*args[1]+args[2]
-
+
+ if isinstance(time, basestring):
+ if (',' not in time) and ('.' not in time):
+ time = time + '.0'
+ expr = r"(\d+):(\d+):(\d+)[,|.](\d+)"
+ finds = re.findall(expr, time)[0]
+ nums = map(float, finds)
+ return ( 3600*int(finds[0])
+ + 60*int(finds[1])
+ + int(finds[2])
+ + nums[3]/(10**len(finds[3])))
+
+ elif isinstance(time, tuple):
+ if len(time)== 3:
+ hr, mn, sec = time
+ elif len(time)== 2:
+ hr, mn, sec = 0, time[0], time[1]
+ return 3600*hr + 60*mn + sec
+
+ else:
+ return time
def deprecated_version_of(f, oldname, newname=None):
""" Indicates that a function is deprecated and has a new name.
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index c03da91e..896923fe 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -27,12 +27,12 @@ from .tools.drawing import blit
from ..Clip import Clip
from ..conf import FFMPEG_BINARY, IMAGEMAGICK_BINARY
from ..tools import (subprocess_call, verbose_print,
- deprecated_version_of)
+ deprecated_version_of)
from ..decorators import (apply_to_mask,
requires_duration,
outplace,
add_mask_if_none,
- time_can_be_tuple)
+ convert_to_seconds)
try:
@@ -117,12 +117,15 @@ class VideoClip(Clip):
# EXPORT OPERATIONS
- @time_can_be_tuple
+ @convert_to_seconds(['t'])
def save_frame(self, filename, t=0, savemask=False):
""" Save a clip's frame to an image file.
Saves the frame of clip corresponding to time ``t`` in
- 'filename'. If ``savemask`` is ``True`` the mask is saved in
+ 'filename'. ``t`` can be expressed in seconds (15.35), in
+ (min, sec), in (hour, min, sec), or as a string: '01:03:05.35'.
+
+ If ``savemask`` is ``True`` the mask is saved in
the alpha layer of the picture.
"""
@@ -861,10 +864,12 @@ class VideoClip(Clip):
# CONVERSIONS TO OTHER TYPES
- @time_can_be_tuple
+ @convert_to_seconds(['t'])
def to_ImageClip(self,t=0, with_mask=True):
"""
- Returns an ImageClip made out of the clip's frame at time ``t``
+ Returns an ImageClip made out of the clip's frame at time ``t``,
+ which can be expressed in seconds (15.35), in (min, sec),
+ in (hour, min, sec), or as a string: '01:03:05.35'.
"""
newclip = ImageClip(self.get_frame(t), ismask=self.ismask)
if with_mask and self.mask is not None:
@@ -1111,9 +1116,12 @@ class TextClip(ImageClip):
-----------
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`` .
+ A string of the text to write. Can be replaced by argument
+ ``filename``.
+
+ filename
+ The name of a file in which there is the text to write.
+ Can be provided instead of argument ``txt``
size
Size of the picture in pixels. Can be auto-set if
@@ -1164,15 +1172,16 @@ class TextClip(ImageClip):
- def __init__(self, txt, size=None, color='black',
+ def __init__(self, txt=None, filename=None, size=None, color='black',
bg_color='transparent', fontsize=None, font='Courier',
stroke_color=None, stroke_width=1, method='label',
kerning=None, align='center', interline=None,
tempfilename=None, temptxt=None,
transparent=True, remove_temp=True,
print_cmd=False):
+
- if not txt.startswith('@'):
+ if txt is not None:
if temptxt is None:
temptxt_fd, temptxt = tempfile.mkstemp(suffix='.txt')
try: # only in Python3 will this work
@@ -1182,7 +1191,8 @@ class TextClip(ImageClip):
os.close(temptxt_fd)
txt = '@'+temptxt
else:
- txt = "'%s'"%txt
+ # use a file instead of a text.
+ txt = "@%"+filename
if size != None:
size = ('' if size[0] is None else str(size[0]),
diff --git a/moviepy/video/fx/all/__init__.py b/moviepy/video/fx/all/__init__.py
index 377e4673..d4749622 100644
--- a/moviepy/video/fx/all/__init__.py
+++ b/moviepy/video/fx/all/__init__.py
@@ -9,13 +9,15 @@ clip = vfx.mirror_x(some_clip)
import os
-directory = os.path.dirname(
+_directory = os.path.dirname(
os.path.dirname(
os.path.realpath(__file__)))
-files = os.listdir(directory)
-fx_list = [f for f in files if ( f.endswith('.py') and not f.startswith('_'))]
-__all__ = [c[:-3] for c in fx_list]
+_files = os.listdir(_directory)
+_fx_list = [_f for _f in _files if ( _f.endswith('.py') and
+ not _f.startswith('_'))]
-for name in __all__:
- exec("from ..%s import %s"%(name,name))
\ No newline at end of file
+__all__ = [_c[:-3] for _c in _fx_list]
+
+for _name in __all__:
+ exec("from ..%s import %s"%(_name,_name))
\ No newline at end of file
diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.py
index 26fb7d01..6258f0ed 100644
--- a/moviepy/video/io/ffmpeg_reader.py
+++ b/moviepy/video/io/ffmpeg_reader.py
@@ -157,10 +157,13 @@ class FFMPEG_VideoReader:
def ffmpeg_read_image(filename, with_mask=True):
- """ Read one image from a file.
+ """ Read an image file (PNG, BMP, JPEG...).
- Wraps FFMPEG_Videoreader to read just one image. Returns an
- ImageClip.
+ Wraps FFMPEG_Videoreader to read just one image.
+ Returns an ImageClip.
+
+ This function is not meant to be used directly in MoviePy,
+ use ImageClip instead to make clips out of image files.
Parameters
-----------
@@ -187,8 +190,7 @@ def ffmpeg_parse_infos(filename, print_infos=False):
Returns a dictionnary with the fields:
"video_found", "video_fps", "duration", "video_nframes",
- "video_duration"
- "audio_found", "audio_fps"
+ "video_duration", "audio_found", "audio_fps"
"video_duration" is slightly smaller than "duration" to avoid
fetching the uncomplete frames at the end, which raises an error.
@@ -229,9 +231,8 @@ def ffmpeg_parse_infos(filename, print_infos=False):
try:
keyword = ('frame=' if is_GIF else 'Duration: ')
line = [l for l in lines if keyword in l][0]
- match = re.search("[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9]", line)
- hms = map(float, line[match.start()+1:match.end()].split(':'))
- result['duration'] = cvsecs(*hms)
+ match = re.findall("([0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9])", line)[0]
+ result['duration'] = cvsecs(match)
except:
raise IOError(("MoviePy error: failed to read the duration of file %s.\n"
"Here are the file infos returned by ffmpeg:\n\n%s")%(
diff --git a/moviepy/video/tools/drawing.py b/moviepy/video/tools/drawing.py
index 98ad13f1..9a6ce88f 100644
--- a/moviepy/video/tools/drawing.py
+++ b/moviepy/video/tools/drawing.py
@@ -109,7 +109,7 @@ def color_gradient(size,p1,p2=None,vector=None, r=None, col1=0,col2=1.0,
Examples
---------
- >>> grad = colorGradient(blabla).astype('unit8')
+ >>> grad = colorGradient(blabla).astype('uint8')
"""
diff --git a/moviepy/video/tools/subtitles.py b/moviepy/video/tools/subtitles.py
index 7f8660f4..33c0d357 100644
--- a/moviepy/video/tools/subtitles.py
+++ b/moviepy/video/tools/subtitles.py
@@ -30,11 +30,9 @@ class SubtitlesClip(VideoClip):
>>> myvideo = VideoFileClip("myvideo.avi")
>>> final = CompositeVideoClip([clip, subtitles])
>>> final.to_videofile("final.mp4", fps=myvideo.fps)
-
-
+
"""
-
def __init__(self, subtitles, make_textclip=None):
VideoClip.__init__(self)
@@ -116,22 +114,6 @@ class SubtitlesClip(VideoClip):
with open(filename, 'w+') as f:
f.write(str(self))
-
-
-def string_to_time(timestring):
- """ Converts a string into seconds """
- nums = map(float, re.findall(r'\d+', timestring))
- return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
-
-
-
-def time_to_string(timestring):
- """ Converts seconds into a string """
- nums = map(float, re.findall(r'\d+', timestring))
- return 3600*nums[0] + 60*nums[1] + nums[2] + nums[3]/1000
-
-
-
def file_to_subtitles(filename):
""" Converts a srt file into subtitles.
@@ -148,9 +130,9 @@ def file_to_subtitles(filename):
current_times , current_text = None, ""
for line in lines:
- times = re.findall("[0-9]*:[0-9]*:[0-9]*,[0-9]*", line)
+ times = re.findall("([0-9]*:[0-9]*:[0-9]*,[0-9]*)", line)
if times != []:
- current_times = map(time_to_string, times)
+ current_times = map(cvsecs, times)
elif line == '\n':
times_texts.append((current_times, current_text.strip('\n')))
current_times, current_text = None, ""
diff --git a/moviepy/video/tools/tracking.py b/moviepy/video/tools/tracking.py
index b5fce40b..ec9fdf1c 100644
--- a/moviepy/video/tools/tracking.py
+++ b/moviepy/video/tools/tracking.py
@@ -12,7 +12,7 @@ from scipy.interpolate import interp1d
from ..io.preview import imdisplay
from .interpolators import Trajectory
-from moviepy.decorators import time_can_be_tuple
+from moviepy.decorators import convert_to_seconds
try:
@@ -28,8 +28,8 @@ except:
# MANUAL TRACKING
-@time_can_be_tuple
-def manual_tracking(clip, t1=None, t2=None, fps=5, nobjects = 1,
+@convert_to_seconds(["t1","t2"])
+def manual_tracking(clip, t1=None, t2=None, fps=None, nobjects = 1,
savefile = None):
"""
Allows manual tracking of an object(s) in the video clip between
@@ -41,37 +41,46 @@ def manual_tracking(clip, t1=None, t2=None, fps=5, nobjects = 1,
object per frame, else returns a list whose elements are of the
form (ti, [(xi1,yi1), (xi2,yi2), ...] )
- :param t1,t2: times during which to track (defaults are start and
- end of the clip)
- :param fps: Number of frames per second to freeze on.
- :param nobjects: Number of objects to click on each frame
+ Parameters
+ -------------
+
+ t1,t2:
+ times during which to track (defaults are start and
+ end of the clip). t1 and t2 can be expressed in seconds
+ like 15.35, in (min, sec), in (hour, min, sec), or as a
+ string: '01:03:05.35'.
+ fps:
+ Number of frames per second to freeze on. If None, the clip's
+ fps attribute is used instead.
+ nobjects:
+ Number of objects to click on each frame.
+ savefile:
+ If provided, the result is saved to a file, which makes
+ it easier to edit and re-use later.
+
+ Examples
+ ---------
-
-
- >>> 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)
+ >>> from moviepy.editor import VideoFileClip
+ >>> from moviepy.tools.tracking import manual_tracking
+ >>> clip = VideoFileClip("myvideo.mp4")
+ >>> # manually indicate 3 trajectories, save them to a file
+ >>> trajectories = manual_tracking(clip, t1=5, t2=7, fps=5,
+ nobjects=3, savefile="track.txt")
+ >>> # ...
+ >>> # LATER, IN ANOTHER SCRIPT, RECOVER THESE TRAJECTORIES
+ >>> from moviepy.tools.tracking import Trajectory
+ >>> traj1, traj2, traj3 = Trajectory.load_list('track.txt')
+ >>> # If ever you only have one object being tracked, recover it with
+ >>> traj, = Trajectory.load_list('track.txt')
"""
import pygame as pg
+ if fps is None:
+ fps = clip.fps
+
screen = pg.display.set_mode(clip.size)
step = 1.0 / fps
if (t1 is None) and (t2 is None):