Skip to content

Video editing with Python

Now rotate allows arbitrary angles. +Various bug fixes.

Zulko98d8ffdcf0a2
diff --git a/README.rst b/README.rst
index 1d5f4c7a..c9541366 100644
--- a/README.rst
+++ b/README.rst
@@ -5,7 +5,7 @@ MoviePy (full documentation here_) is a Python module for video editing: cuts, c
MoviePy can read and write all the most common audio and video formats, including GIF, and runs on Windows/Mac/Linux, with Python 2.7+ and 3. Here it is in action in an IPython notebook:
-.. image:: https://raw.githubusercontent.com/Zulko/moviepy/master/docs/demo_preview_small.jpeg
+.. image:: https://raw.githubusercontent.com/Zulko/moviepy/master/docs/demo_preview.jpeg
:alt: [logo]
:align: center
diff --git a/docs/demo_preview.jpeg b/docs/demo_preview.jpeg
index 7160f512..ce14ae82 100644
Binary files a/docs/demo_preview.jpeg and b/docs/demo_preview.jpeg differ
diff --git a/docs/demo_preview_small.jpeg b/docs/demo_preview_small.jpeg
deleted file mode 100644
index 1e0d4cf6..00000000
Binary files a/docs/demo_preview_small.jpeg and /dev/null differ
diff --git a/docs/getting_started/quick_presentation.rst b/docs/getting_started/quick_presentation.rst
index 418c73d7..b6a88b21 100644
--- a/docs/getting_started/quick_presentation.rst
+++ b/docs/getting_started/quick_presentation.rst
@@ -18,7 +18,7 @@ Here are a few reasons why you may want to edit videos in Python:
And here are a few uses for which MoviePy is NOT the best solution:
-- You only need to do frame-by-frame video analysis (with face detection or other fancy stuff). This could be done with MoviePy in association with other libraries, but really, just use OpenCV or SimpleCV, these are libraries that specialize in these tasks.
+- You only need to do frame-by-frame video analysis (with face detection or other fancy stuff). This could be done with MoviePy in association with other libraries, but really, just use imageio_, OpenCV_ or SimpleCV, these are libraries that specialize in these tasks.
- You only want to convert a video file, or turn a series of image files into a movie. In this case it is better to directly call ``ffmpeg`` (or ``avconv`` or ``mencoder``...) it will be faster more memory-efficient than going through MoviePy.
@@ -31,7 +31,7 @@ MoviePy has been developed with the following goals in mind:
- **Flexible**. You have total control over the frames of the video and audio, and creating your own effects is easy as Py.
- **Portable**. The code uses very common software (Numpy and FFMPEG) and can run on (almost) any machine with (almost) any version of Python.
-Now for the main limitations: MoviePy cannot (yet) stream videos (read from a webcam, or render a video live on a distant machine), it cannot do 3D effects (by lack of a nice 3D library for Python) and is not really designed for video processing involving many successive frames of a movie (like video stabilization, you'll need another software for that).
+For the limitations: MoviePy cannot (yet) stream videos (read from a webcam, or render a video live on a distant machine), and is not really designed for video processing involving many successive frames of a movie (like video stabilization, you'll need another software for that). You can also have memory problems if you use many video, audio, and image sources at the same time (>100), but this will be fixed in future versions.
Example code
~~~~~~~~~~~~~~
@@ -80,6 +80,9 @@ You will also find a few advanced goodies in ``moviepy.video.tools`` to track ob
Finally, although MoviePy has no graphical user interface, there are many ways to preview a clip which allow you to fine-tune your scripts and be sure that everything is perfect when you render you video in high quality. See :ref:`efficient`.
+.. _imageio: http://imageio.github.io/
+.. _OpenCV: http://opencv.org/
+
diff --git a/moviepy/Clip.py b/moviepy/Clip.py
index 3cba0c89..8655d56b 100644
--- a/moviepy/Clip.py
+++ b/moviepy/Clip.py
@@ -385,17 +385,17 @@ class Clip:
"duration (%.02f)."%self.duration)
newclip = self.fl_time(lambda t: t + t_start, apply_to=[])
-
+
if (t_end is None) and (self.duration is not None):
t_end = self.duration
- elif t_end<0:
+ elif (t_end is not None) and (t_end<0):
if self.duration is None:
- print ("Error: subclip with negative times can only be"+
- "extracted from clips with a ``duration``")
+ print ("Error: subclip with negative times (here %s)"%(str((t_start, t_end)))
+ +" can only be extracted from clips with a ``duration``")
else:
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index 1088f5b4..7c60902d 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -14,7 +14,7 @@ from copy import copy
from tqdm import tqdm
import numpy as np
-from imageio import imread
+from imageio import imread, imsave
import moviepy.audio.io as aio
from .io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_video
@@ -138,15 +138,15 @@ class VideoClip(Clip):
"""
- im = self.get_frame(t)
- if im.dtype != "uint8":
- im = im.astype("uint8")
+ im = self.get_frame(t)
if withmask and self.mask is not None:
mask = 255 * self.mask.get_frame(t)
im = np.dstack([im, mask]).astype('uint8')
+ else:
+ im = im.astype("uint8")
- ffmpeg_write_image(filename, im)
+ imsave(filename, im)
@requires_duration
@@ -394,7 +394,7 @@ class VideoClip(Clip):
filenames = []
total = int(self.duration / fps) + 1
for i, t in tqdm(enumerate(tt), total=total):
- name = nameformat % (i + 1)
+ name = nameformat % i
filenames.append(name)
self.save_frame(name, t, withmask=withmask)
@@ -788,6 +788,35 @@ class VideoClip(Clip):
+class DataVideoClip(VideoClip):
+ """
+ Class of video clips whose successive frames are functions
+ of successive datasets
+
+ Parameters
+ -----------
+ data
+ A liste of datasets, each dataset being used for one frame of the clip
+
+ data_to_frame
+ A function d -> video frame, where d is one element of the list `data`
+
+ fps
+ Number of frames per second in the animation
+
+ Examples
+ ---------
+ """
+
+ def __init__(self, data, data_to_frame, fps, ismask=False,
+ has_constant_size=True):
+ self.data = data
+ self.data_to_frame = data_to_frame
+ self.fps=fps
+ make_frame = lambda t: self.data_to_frame( self.data[int(self.fps*t)])
+ VideoClip.__init__(self, make_frame, ismask=ismask,
+ duration=1.0*len(data)/fps, has_constant_size=has_constant_size)
+
diff --git a/moviepy/video/fx/freeze.py b/moviepy/video/fx/freeze.py
index 2a0dfea7..17d8c7d0 100644
--- a/moviepy/video/fx/freeze.py
+++ b/moviepy/video/fx/freeze.py
@@ -17,11 +17,12 @@ def freeze(clip, t=0, freeze_duration=None, total_duration=None,
if t=='end':
t = clip.duration - padding_end
-
+ print t
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 []
+ #print after[0].duration, freeze[0].duration
return concatenate_videoclips(before+freeze+after)
\ No newline at end of file
diff --git a/moviepy/video/fx/resize.py b/moviepy/video/fx/resize.py
index 27d11af2..85d1ffb2 100644
--- a/moviepy/video/fx/resize.py
+++ b/moviepy/video/fx/resize.py
@@ -29,8 +29,10 @@ except ImportError:
pilim = Image.fromarray(pic)
resized_pil = pilim.resize(newsize[::-1], Image.ANTIALIAS)
- arr = np.fromstring(resized_pil.tostring(), dtype='uint8')
- return arr.reshape(newshape)
+ #arr = np.fromstring(resized_pil.tostring(), dtype='uint8')
+ #arr.reshape(newshape)
+ return np.array(resized_pil)
+
resizer.origin = "PIL"
except ImportError:
diff --git a/moviepy/video/fx/rotate.py b/moviepy/video/fx/rotate.py
index 9299cd90..5755ff54 100644
--- a/moviepy/video/fx/rotate.py
+++ b/moviepy/video/fx/rotate.py
@@ -1,24 +1,71 @@
+from moviepy.decorators import apply_to_mask
import numpy as np
+try:
+ from PIL import Image
+ PIL_FOUND = True
+ def pil_rotater(pic, angle, resample, expand):
+ return np.array( Image.fromarray(pic).rotate(angle, expand=expand,
+ resample=resample))
+except ImportError:
+ PIL_FOUND = False
-def rotate(clip, angle, apply_to_mask=True, unit='deg'):
-
- if unit == 'rad':
- angle = 360*angle/(2*3.14159)
+def rotate(clip, angle, unit='deg', resample="bicubic", expand=True):
+ """
+ Change unit to 'rad' to define angles as radians.
+ If the angle is not one of 90, 180, -90, -180 (degrees) there will be
+ black borders. You can make them transparent with
+
+ >>> newclip = clip.add_mask().rotate(72)
+
+ Parameters
+ ===========
+
+ clip
+ A video clip
+
+ angle
+ Either a value or a function angle(t) representing the angle of rotation
+
+ unit
+ Unit of parameter `angle` (either `deg` for degrees or `rad` for radians)
+
+ resample
+ One of "nearest", "bilinear", or "bicubic".
+
+ expand
+ Only applIf False, the clip will maintain the same True, the clip will be resized so that the whole
+ """
+ resample = {"bilinear": Image.BILINEAR,
+ "nearest": Image.NEAREST,
+ "bicubic": Image.BICUBIC}[resample]
+
+ if not hasattr(angle, '__call__'):
+ # if angle is a constant, convert to a constant function
+ a = +angle
+ angle = lambda t: a
+
transpo = [1,0] if clip.ismask else [1,0,2]
- angle_transfo = {
- 90 : lambda im : np.transpose(im, axes=transpo)[::-1],
- -90: lambda im : np.transpose(im, axes=transpo)[:,::-1],
- 180: lambda im : im[::-1,::-1]}
-
- if angle in angle_transfo:
- newclip = clip.fl_image( angle_transfo[angle])
- else:
- raise ValueError('Angle not supported, only 90, -90, 180 at the moment')
-
- if apply_to_mask and (newclip.mask is not None):
- newclip.mask = newclip.mask.fx( rotation, angle,
- apply_to_mask=False,
- unit=unit)
-
- return newclip
+
+ def fl(gf, t):
+
+ a = angle(t)
+ im = gf(t)
+
+ if unit == 'rad':
+ a = 360.0*a/(2*np.pi)
+
+ if (a==90) and expand:
+ return np.transpose(im, axes=transpo)[::-1]
+ elif (a==-90) and expand:
+ return np.transpose(im, axes=transpo)[:,::-1]
+ elif (a in [180, -180]) and expand:
+ return im[::-1,::-1]
+ elif not PIL_FOUND:
+ raise ValueError('Without "Pillow" installed, only angles 90, -90,'
+ '180 are supported, please install "Pillow" with'
+ "pip install pillow")
+ else:
+ return pil_rotater(im, a, resample=resample, expand=expand)
+
+ return clip.fl(fl, apply_to=["mask"])
\ No newline at end of file
diff --git a/moviepy/video/io/ImageSequenceClip.py b/moviepy/video/io/ImageSequenceClip.py
index 041fdefa..ced0f7b3 100644
--- a/moviepy/video/io/ImageSequenceClip.py
+++ b/moviepy/video/io/ImageSequenceClip.py
@@ -50,7 +50,9 @@ class ImageSequenceClip(VideoClip):
ismask=False, load_images=False):
# CODE WRITTEN AS IT CAME, MAY BE IMPROVED IN THE FUTURE
-
+
+ if (fps is None) and (duration is None):
+ raise ValueError("Please provide either 'fps' or 'durations'.")
VideoClip.__init__(self, ismask=ismask)
# Parse the data
@@ -90,6 +92,7 @@ class ImageSequenceClip(VideoClip):
self.lastindex = None
self.lastimage = None
+ print "lol"
def make_frame(t):
@@ -101,7 +104,7 @@ class ImageSequenceClip(VideoClip):
return self.lastimage
- if with_mask and (make_frame(0).shape[2]==4):
+ if with_mask and (imread(self.sequence[0]).shape[2]==4):
self.mask = VideoClip(ismask=True)
@@ -109,7 +112,8 @@ class ImageSequenceClip(VideoClip):
index = find_image_index(t)
if index != self.lastindex:
- self.mask.lastimage = imread(self.sequence[index])[:,:,3]
+ frame = imread(self.sequence[index])[:,:,3]
+ self.mask.lastimage = frame.astype(float)/255
self.mask.lastindex = index
return self.mask.lastimage
@@ -123,7 +127,18 @@ class ImageSequenceClip(VideoClip):
def make_frame(t):
index = find_image_index(t)
- return self.sequence[index]
+ return self.sequence[index][:,:,:3]
+
+ if with_mask and (self.sequence[0].shape[2]==4):
+
+ self.mask = VideoClip(ismask=True)
+
+ def mask_make_frame(t):
+ index = find_image_index(t)
+ return 1.0*self.sequence[index][:,:,3]/255
+
+ self.mask.make_frame = mask_make_frame
+ self.mask.size = mask_make_frame(0).shape[:2][::-1]
self.make_frame = make_frame
diff --git a/moviepy/video/io/bindings.py b/moviepy/video/io/bindings.py
index ac6ffa95..3dd8ca27 100644
--- a/moviepy/video/io/bindings.py
+++ b/moviepy/video/io/bindings.py
@@ -6,14 +6,16 @@ modules (PIL, matplotlib, mayavi, etc.)
import numpy as np
def PIL_to_npimage(im):
- """ Transforms a PIL/Pillow image into a numpy RGB(A) image. """
- w,h = im.size
- d = (4 if im.mode=="RGBA" else 3)
- return +np.frombuffer(im.tobytes(), dtype='uint8').reshape((h,w,d))
+ """ Transforms a PIL/Pillow image into a numpy RGB(A) image.
+ Actually all this do is returning numpy.array(im)."""
+ return np.array(im)
+ #w,h = im.size
+ #d = (4 if im.mode=="RGBA" else 3)
+ #return +np.frombuffer(im.tobytes(), dtype='uint8').reshape((h,w,d))
def mplfig_to_npimage(fig):
- """ Updates the canvas and returns the RGB image (np array) """
+ """ Converts a matplotlib figure to a RGB frame after updating the canvas"""
fig.canvas.draw() # update/draw the elements
w,h = fig.canvas.get_width_height()
buf = fig.canvas.tostring_rgb()
diff --git a/moviepy/video/io/downloader.py b/moviepy/video/io/downloader.py
index 4a582b4f..cd3df06f 100644
--- a/moviepy/video/io/downloader.py
+++ b/moviepy/video/io/downloader.py
@@ -24,7 +24,11 @@ def download_webfile(url, filename, overwrite=False):
if '.' in url:
urlretrieve(url, filename)
else:
- subprocess_call(['youtube-dl', url, '-o', filename])
-
+ try:
+ subprocess_call(['youtube-dl', url, '-o', filename])
+ except OSError as e:
+ raise OSError(e.message + '\n A possible reason is that youtube-dl'
+ ' is not installed on your computer. Install it with '
+ ' "pip install youtube-dl"')
diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.py
index a973471c..60501520 100644
--- a/moviepy/video/io/ffmpeg_writer.py
+++ b/moviepy/video/io/ffmpeg_writer.py
@@ -164,12 +164,17 @@ class FFMPEG_VideoWriter:
"video codec."
)%(self.codec, self.ext)
- elif "encoder setup failed":
+ elif "encoder setup failed" in ffmpeg_error:
error = error+("\n\nThe video export "
"failed, possibly because the bitrate you specified "
"was too high or too low for the video codec.")
+ elif "Invalid encoder type" in ffmpeg_error:
+
+ error = error + ("\n\nThe video export failed because the codec "
+ "or file extension you provided is not a video")
+
raise IOError(error)
diff --git a/moviepy/video/tools/cuts.py b/moviepy/video/tools/cuts.py
index 5088d6e0..dbf21901 100644
--- a/moviepy/video/tools/cuts.py
+++ b/moviepy/video/tools/cuts.py
@@ -45,10 +45,12 @@ class FramesMatch:
self.time_span = t2-t1
def __str__(self):
- return '(%.04f, %.04f, %.04f)'%(self.t1, self.t2, self.d_min, self.d_max)
+ return '(%.04f, %.04f, %.04f, %.04f)'%(
+ self.t1, self.t2, self.d_min, self.d_max)
def __repr__(self):
- return '(%.04f, %.04f, %.04f)'%(self.t1, self.t2, self.d_min, self.d_max)
+ return '(%.04f, %.04f, %.04f, %.04f)'%(
+ self.t1, self.t2, self.d_min, self.d_max)
def __iter__(self):
return [self.t1, self.t2, self.d_min, self.d_max].__iter__()
diff --git a/moviepy/video/tools/drawing.py b/moviepy/video/tools/drawing.py
index 40891dea..7be3bd09 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('uint8')
+ >>> grad = color_gradient(blabla).astype('uint8')
"""
@@ -121,7 +121,7 @@ def color_gradient(size,p1,p2=None,vector=None, r=None, col1=0,col2=1.0,
if shape == 'bilinear':
if vector is None:
vector = np.array(p2) - np.array(p1)
- m1,m2 = [ colorGradient(size, p1, vector=v, col1 = 1.0, col2 = 0,
+ m1,m2 = [ color_gradient(size, p1, vector=v, col1 = 1.0, col2 = 0,
shape = 'linear', offset= offset)
for v in [vector,-vector]]
@@ -216,7 +216,7 @@ def color_split(size,x=None,y=None,p1=None,p2=None,vector=None,
>>> # an image with all pixels with y<50 red, the others green
>>> 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)
+ >>> color_split(size, p1=[20,50], p2=[25,70] col1=0, col2=1)
"""