Skip to content

Video editing with Python

Many misc. changes. Now resize(width= can be a function. Fixed blackwhite. Fixed write_gif(ffmpeg). More in subtitles. New class for tracking.

Zulkob62eaf9c3d74
diff --git a/docs/crash_course/crash_course.rst b/docs/crash_course/crash_course.rst
index f0cc1314..6c6d98bf 100644
--- a/docs/crash_course/crash_course.rst
+++ b/docs/crash_course/crash_course.rst
@@ -129,7 +129,7 @@ When indicating the position keep in mind that the ``y`` coordinate has its zero
.. _renderingAClip:
-Wrting a video clip to a file
+Writing a video clip to a file
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To write a clip as a video file, use ::
@@ -156,9 +156,9 @@ To write your video as an animated GIF, use ::
my_clip.write_gif('test.gif', fps=12)
-If your computer has enough RAM (say, at least 2GB), you can use its faster version
+If your computer has enough RAM (say, at least 2GB), you can use its faster version ``write_gif2``:
- my_clip.write_gif('test.gif', fps=12)
+ my_clip.write_gif2('test.gif', fps=12)
See `this blog post <http://zulko.github.io/blog/2014/01/23/making-animated-gifs-from-video-files-with-python>`_ for more informations on making GIFs with MoviePy.
diff --git a/moviepy/Clip.py b/moviepy/Clip.py
index 9b99333e..bf30894d 100644
--- a/moviepy/Clip.py
+++ b/moviepy/Clip.py
@@ -12,7 +12,7 @@ from moviepy.decorators import ( apply_to_mask,
time_can_be_tuple,
requires_duration,
outplace)
-
+from tqdm import tqdm
class Clip:
@@ -368,7 +368,7 @@ class Clip:
if they exist.
"""
- fl = lambda t: t + (0 if (t < ta) else tb - ta)
+ fl = lambda t: t + (t >= ta)*(tb - ta)
newclip = self.fl_time(fl)
if self.duration != None:
return newclip.set_duration(self.duration - (tb - ta))
@@ -376,7 +376,7 @@ class Clip:
return newclip
@requires_duration
- def iter_frames(self, fps=None):
+ def iter_frames(self, fps=None, progress_bar=False):
""" Iterates over all the frames of the clip.
Returns each frame of the clip as a HxWxN np.array,
@@ -402,6 +402,15 @@ class Clip:
if fps is None:
fps = self.fps
-
- for t in np.arange(0, self.duration, 1.0/fps):
- yield self.get_frame(t)
+
+ def generator():
+ for t in np.arange(0, self.duration, 1.0/fps):
+ yield self.get_frame(t)
+
+ if progress_bar:
+ nframes = int(self.duration*fps)+1
+ return tqdm(generator(), total=nframes)
+
+ return generator()
+
+
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index b32518a7..f2a39c2c 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -17,23 +17,22 @@ from tqdm import tqdm
import numpy as np
-from moviepy.decorators import (apply_to_mask,
- requires_duration,
- outplace,
- add_mask_if_none,
- time_can_be_tuple)
-
-from moviepy.tools import (subprocess_call, verbose_print,
- deprecated_version_of)
-
import moviepy.audio.io as aio
from .io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_video
from .io.ffmpeg_reader import ffmpeg_read_image
from .io.ffmpeg_tools import ffmpeg_merge_video_audio
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)
+from ..decorators import (apply_to_mask,
+ requires_duration,
+ outplace,
+ add_mask_if_none,
+ time_can_be_tuple)
try:
@@ -476,7 +475,7 @@ class VideoClip(Clip):
cmd = [FFMPEG_BINARY, '-y',
'-f', 'image2', '-r',str(fps),
- '-i', fileName+'_GIFTEMP%04d.bmp',
+ '-i', fileName+'_GIFTEMP%04d.png',
'-r',str(fps),
filename]
@@ -1030,7 +1029,7 @@ class ImageClip(VideoClip):
"""
# When we use fl on an image clip it may become animated.
- #Therefore the result is not an ImageClip, just a VideoClip.
+ # Therefore the result is not an ImageClip, just a VideoClip.
newclip = VideoClip.fl(self,fl, apply_to=apply_to,
keep_duration=keep_duration)
newclip.__class__ = VideoClip
diff --git a/moviepy/video/fx/blackwhite.py b/moviepy/video/fx/blackwhite.py
index 95c54e12..b17c0fe1 100644
--- a/moviepy/video/fx/blackwhite.py
+++ b/moviepy/video/fx/blackwhite.py
@@ -2,10 +2,18 @@ import numpy as np
def blackwhite(clip, RGB = [1,1,1], preserve_luminosity=True):
""" Desaturates the picture, makes it black and white.
- If RBG is 'CRT_phosphor' a special set of values is used.
- preserve_luminosity does nothing right now.
- method = sum (TODO: others) """
+ Parameter RGB allows to set weights for the different color
+ channels.
+ If RBG is 'CRT_phosphor' a special set of values is used.
+ preserve_luminosity maintains the sum of RGB to 1."""
+
if RGB == 'CRT_phosphor':
RGB = [0.2125, 0.7154, 0.0721]
-
- return clip.fl_image(lambda im: np.dstack(3*[im.sum(axis=2)/3]) )
+
+ 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
+ return np.dstack(3*[im]).astype('uint8')
+
+ return clip.fl_image(fl)
diff --git a/moviepy/video/fx/resize.py b/moviepy/video/fx/resize.py
index b80167c5..5d0c7730 100644
--- a/moviepy/video/fx/resize.py
+++ b/moviepy/video/fx/resize.py
@@ -42,9 +42,8 @@ except ImportError:
from moviepy.decorators import apply_to_mask
-
-@apply_to_mask
-def resize(clip, newsize=None, height=None, width=None):
+
+def resize(clip, newsize=None, height=None, width=None, apply_to_mask=True):
"""
Returns a video clip that is a resized version of the clip.
@@ -99,7 +98,8 @@ def resize(clip, newsize=None, height=None, width=None):
fun = lambda gf,t: resizer(gf(t).astype('uint8'),
newsize2(t))
- return clip.fl(fun, keep_duration=True)
+ return clip.fl(fun, keep_duration=True,
+ apply_to= (["mask"] if apply_to_mask else []))
else:
@@ -108,9 +108,20 @@ def resize(clip, newsize=None, height=None, width=None):
elif height != None:
- newsize = [w * height / h, height]
+ if hasattr(height, "__call__"):
+ fun = lambda t : 1.0*int(height(t))/h
+ return resize(clip, fun)
+
+
+ else:
+
+ newsize = [w * height / h, height]
elif width != None:
+
+ if hasattr(width, "__call__"):
+ fun = lambda t : 1.0*width(t)/w
+ return resize(clip, fun)
newsize = [width, h * width / w]
@@ -119,13 +130,13 @@ def resize(clip, newsize=None, height=None, width=None):
if clip.ismask:
fl = lambda pic: 1.0*resizer((255 * pic).astype('uint8'),
- newsize)/255
+ newsize)/255
else:
fl = lambda pic: resizer(pic.astype('uint8'), newsize)
- return clip.fl_image(fl, apply_to='mask')
+ return clip.fl_image(fl, apply_to= (["mask"] if apply_to_mask else []))
if not resize_possible:
diff --git a/moviepy/video/io/preview.py b/moviepy/video/io/preview.py
index e8f2e9de..b0d6dd59 100644
--- a/moviepy/video/io/preview.py
+++ b/moviepy/video/io/preview.py
@@ -121,7 +121,7 @@ def preview(clip, fps=15, audio=True, audio_fps=22050,
result = []
t0 = time.time()
- for t in np.arange(1.0 / fps, clip.duration, 1.0 / fps):
+ for t in np.arange(1.0 / fps, clip.duration-.001, 1.0 / fps):
img = clip.get_frame(t)
diff --git a/moviepy/video/tools/drawing.py b/moviepy/video/tools/drawing.py
index afb35c30..98ad13f1 100644
--- a/moviepy/video/tools/drawing.py
+++ b/moviepy/video/tools/drawing.py
@@ -212,9 +212,9 @@ def color_split(size,x=None,y=None,p1=None,p2=None,vector=None,
>>> size = [200,200]
>>> # an image with all pixels with x<50 =0, the others =1
- >>> colorSplit(size, x=50, col1=0, col2=1)
+ >>> color_split(size, x=50, col1=0, col2=1)
>>> # an image with all pixels with y<50 red, the others green
- >>> colorSplit(size, x=50, col1=[255,0,0], col2=[0,255,0])
+ >>> color_split(size, x=50, col1=[255,0,0], col2=[0,255,0])
>>> # An image splitted along an arbitrary line (see below)
>>> colorSplit(size, p1=[20,50], p2=[25,70] col1=0, col2=1)
@@ -223,6 +223,14 @@ def color_split(size,x=None,y=None,p1=None,p2=None,vector=None,
if grad_width or ( (x is None) and (y is None)):
if p2 != None:
vector = (np.array(p2) - np.array(p1))
+ elif x is not None:
+ vector = np.array([0,1.0])
+ p1 = np.array([x, 0])
+ print vector, p1
+ elif y is not None:
+ vector = np.array([1.0, 0.0])
+ p1 = np.array([0,y])
+
x,y = vector
vector = np.array([y,-x]).astype('float')
norm = np.linalg.norm(vector)
diff --git a/moviepy/video/tools/subtitles.py b/moviepy/video/tools/subtitles.py
index 10a9a5d2..7f8660f4 100644
--- a/moviepy/video/tools/subtitles.py
+++ b/moviepy/video/tools/subtitles.py
@@ -5,6 +5,7 @@ import numpy as np
from moviepy.video.VideoClip import VideoClip, TextClip
from moviepy.tools import cvsecs
+
class SubtitlesClip(VideoClip):
""" A Clip that serves as "subtitle track" in videos.
@@ -32,19 +33,25 @@ class SubtitlesClip(VideoClip):
"""
+
+
def __init__(self, subtitles, make_textclip=None):
VideoClip.__init__(self)
if isinstance( subtitles, str):
subtitles = file_to_subtitles(subtitles)
+
subtitles = [(map(cvsecs, tt),txt) for tt, txt in subtitles]
self.subtitles = subtitles
self.textclips = dict()
+
if make_textclip is None:
+
make_textclip = lambda txt: TextClip(txt, font='Georgia-Bold',
fontsize=24, color='white',
stroke_color='black', stroke_width=0.5)
+
self.make_textclip = make_textclip
self.start=0
self.duration = max([tb for ((ta,tb), txt) in self.subtitles])
@@ -76,12 +83,18 @@ class SubtitlesClip(VideoClip):
self.get_frame = get_frame
self.mask = VideoClip(ismask=True, get_frame=mask_get_frame)
+
+
def __iter__(self):
return self.subtitles.__iter__()
+
+
def __getitem__(self, k):
return self.subtitles[k]
+
+
def __str__(self):
def to_srt(sub_element):
@@ -91,27 +104,34 @@ class SubtitlesClip(VideoClip):
return "\n\n".join(map(to_srt, self.subtitles))
+
+
def match_expr(self, expr):
return SubtitlesClip([e for e in self.subtitles
if re.find(expr, e) != []])
+
def write_srt(self, filename):
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 a string into seconds """
+ """ 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.
@@ -136,5 +156,4 @@ def file_to_subtitles(filename):
current_times, current_text = None, ""
elif current_times is not None:
current_text = current_text + line
-
return times_texts
\ No newline at end of file
diff --git a/moviepy/video/tools/tracking.py b/moviepy/video/tools/tracking.py
index 06f2593a..b5fce40b 100644
--- a/moviepy/video/tools/tracking.py
+++ b/moviepy/video/tools/tracking.py
@@ -10,41 +10,27 @@ of the tracking time interval).
from scipy.interpolate import interp1d
-from moviepy.video.io.preview import imdisplay
+from ..io.preview import imdisplay
+from .interpolators import Trajectory
+from moviepy.decorators import time_can_be_tuple
+
try:
import cv2
+ autotracking_possible = True
except:
# Note: this will be later fixed with scipy/skimage replacements
# but for the moment OpenCV is mandatory, so...
- print("WARNING: OpenCV not found: automated tracking not possible")
-
+ autotracking_possible = False
# WE START WITH A TOOL FUNCTION
-def to_fxfy(txy_list, **kwargs):
- """ Transforms a list [ (ti, (xi,yi)) ] into 2 functions (fx,fy)
- where fx : t -> x(t) and fy : t -> y(t).
- If the time t is out of the bounds of the tracking time interval
- fx and fy return the position of the object at the start or at
- the end of the tracking time interval.
- Keywords can be passed to decide the kind of interpolation,
- see the doc of ``scipy.interpolate.interp1d``."""
-
- tt, xx, yy = zip(*txy_list)
- interp_x = interp1d(tt, xx, **kwargs)
- interp_y = interp1d(tt, yy, **kwargs)
- fx = lambda t: xx[0] if (t <= tt[0]) else ( xx[-1] if t >= tt[-1]
- else ( interp_x(t) ) )
- fy = lambda t: yy[0] if (t <= tt[0]) else ( yy[-1] if t >= tt[-1]
- else ( interp_y(t) ) )
- return fx,fy
-
-
# MANUAL TRACKING
-def manual_tracking(clip, t1=None, t2=None, fps=5, nobjects = 1):
+@time_can_be_tuple
+def manual_tracking(clip, t1=None, t2=None, fps=5, nobjects = 1,
+ savefile = None):
"""
Allows manual tracking of an object(s) in the video clip between
times `t1` and `t2`. This displays the clip frame by frame
@@ -107,6 +93,8 @@ def manual_tracking(clip, t1=None, t2=None, fps=5, nobjects = 1):
if event.type == pg.KEYDOWN:
if (event.key == pg.K_BACKSLASH):
return "return"
+ elif (event.key == pg.K_ESCAPE):
+ raise KeyboardInterrupt()
elif event.type == pg.MOUSEBUTTONDOWN:
@@ -114,7 +102,7 @@ def manual_tracking(clip, t1=None, t2=None, fps=5, nobjects = 1):
clicks.append((x, y))
objects_to_click -= 1
- return clicks if (len(clicks)>1) else clicks[0]
+ return clicks
while t < t2:
@@ -126,11 +114,16 @@ def manual_tracking(clip, t1=None, t2=None, fps=5, nobjects = 1):
txy_list.append((t,clicks))
t += step
- return txy_list, to_fxfy(txy_list)
-
-
-
-
+ tt, xylist = zip(*txy_list)
+ result = []
+ for i in range(nobjects):
+ xys = [e[i] for e in xylist]
+ xx, yy = zip(*xys)
+ result.append(Trajectory(tt, xx, yy))
+
+ if savefile is not None:
+ Trajectory.save_list(result, savefile)
+ return result
# AUTOMATED TRACKING OF A PATTERN
@@ -164,6 +157,12 @@ def autoTrack(clip, pattern, tt=None, fps=None, radius=20, xy0=None):
to -1 the pattern will be searched in the whole screen at each frame).
You can also provide the original position of the pattern with xy0.
"""
+
+ if not autotracking_possible:
+ raise IOError("Sorry, autotrack requires OpenCV for the moment. "
+ "Install OpenCV (aka cv2) to use it.")
+
+
if not xy0:
xy0 = findAround(clip.get_frame(tt[0]),pattern)
@@ -176,5 +175,5 @@ def autoTrack(clip, pattern, tt=None, fps=None, radius=20, xy0=None):
xy=xys[-1],r=radius))
xx,yy = zip(*xys)
- txy_list = zip(tt,xx,yy)
- return txy_list, to_fxfy(txy_list)
+
+ return Trajectory(tt, xx, yy)