Skip to content

Video editing with Python

Towards Python3 compatibility

Zulko252f175679f4
diff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.py
index 5beb5c1f..0d2bf251 100644
--- a/moviepy/audio/AudioClip.py
+++ b/moviepy/audio/AudioClip.py
@@ -107,7 +107,7 @@ class AudioArrayClip(AudioClip):
self.duration = 1.0 * len(array) / fps
- def get_framef(t):
+ def get_frame(t):
""" complicated, but must be able to handle the case where t
is a list of the form sin(t) """
diff --git a/moviepy/audio/fx/__init__.py b/moviepy/audio/fx/__init__.py
index a58dd727..aec556c7 100644
--- a/moviepy/audio/fx/__init__.py
+++ b/moviepy/audio/fx/__init__.py
@@ -11,4 +11,4 @@ fx_list = [f for f in files if ( f.endswith('py') and not f.startswith('_'))]
__all__ = [c[:-3] for c in fx_list]
for name in __all__:
- exec("from %s import %s"%(name,name))
+ exec("from .%s import %s"%(name,name))
diff --git a/moviepy/audio/io/AudioFileClip.py b/moviepy/audio/io/AudioFileClip.py
index 9cb35183..33cd305f 100644
--- a/moviepy/audio/io/AudioFileClip.py
+++ b/moviepy/audio/io/AudioFileClip.py
@@ -1,3 +1,5 @@
+from __future__ import division
+
import wave
import numpy as np
@@ -42,15 +44,17 @@ class AudioFileClip(AudioClip):
Clip.__init__(self)
self.filename = filename
- self.reader = FFMPEG_AudioReader(filename,fps=fps,nbytes=nbytes)
+ self.reader = FFMPEG_AudioReader(filename,fps=fps,nbytes=nbytes,
+ bufsize=buffersize+100)
self.fps = fps
self.duration = self.reader.duration
+ self.end = self.duration
+
self.nframes = self.reader.nframes
self.buffersize= buffersize
- self.buffer=None
+ self.buffer= None
self._fstart_buffer = 1
self._buffer_around(1)
- self.nchannels = self.reader.nchannels
def gf(t):
bufsize = self.buffersize
@@ -75,7 +79,7 @@ class AudioFileClip(AudioClip):
" buffer too small.")
raise
else:
- ind = int(self.fps*t)+1
+ ind = int(self.fps*t)#+1
if ind<1 or ind> self.nframes: # out of time: return 0
return np.zeros(self.nchannels)
@@ -87,13 +91,22 @@ class AudioFileClip(AudioClip):
return self.buffer[ind - self._fstart_buffer]
self.get_frame = gf
-
+
+ @property
+ def nchannels(self):
+ """
+ returns the number of channels of the reader
+ (1: mono, 2: stereo)
+ """
+ return self.reader.nchannels
+
def _buffer_around(self,framenumber):
- """ fill the buffer with frames, centered on ``framenumber``
- if possible
"""
- # start frame for the buffer
- fbuffer = framenumber - self.buffersize/2
+ fill the buffer with frames, centered on ``framenumber``
+ if possible
+ """
+ # start frame for the buffer
+ fbuffer = framenumber - self.buffersize//2
fbuffer = max(1, fbuffer)
diff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.py
index 4f9f1857..768ddffb 100644
--- a/moviepy/audio/io/ffmpeg_audiowriter.py
+++ b/moviepy/audio/io/ffmpeg_audiowriter.py
@@ -1,3 +1,5 @@
+from __future__ import division
+
import sys
import wave
import numpy as np
@@ -55,8 +57,8 @@ class FFMPEG_AudioWriter:
stderr=sp.PIPE)
def write_frames(self,frames_array):
- #self.proc.stdin.write(img_array.tostring())
- frames_array.tofile(self.proc.stdin)
+ self.proc.stdin.write(frames_array.tostring())
+ #frames_array.tofile(self.proc.stdin) # only python 2.7
def close(self):
self.proc.stdin.close()
@@ -80,9 +82,8 @@ def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
codec=codec, bitrate=bitrate)
totalsize = int(fps*clip.duration)
- nchunks = totalsize / buffersize + 1
+ nchunks = totalsize // buffersize + 1
pospos = np.array(list(range(0, totalsize, buffersize))+[totalsize])
- ifeedback = max(1,nchunks/10)
for i in tqdm(range(nchunks)):
tt = (1.0/fps)*np.arange(pospos[i],pospos[i+1])
diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.py
index 7cdc03eb..43b16390 100644
--- a/moviepy/audio/io/readers.py
+++ b/moviepy/audio/io/readers.py
@@ -1,23 +1,19 @@
import subprocess as sp
import re
-import time
-import os
import numpy as np
-
-#from moviepy.clip import Clip
from moviepy.tools import cvsecs
from moviepy.conf import FFMPEG_BINARY
-from moviepy.tools import cvsecs
class FFMPEG_AudioReader:
""" streams any file (audio or video) and outputs a 16bit 44100HZ
wav that can be read by the moviepy AudioFileClip. """
- def __init__(self, filename, print_infos=False, fps=44100, nbytes=2):
+ def __init__(self, filename, bufsize, print_infos=False, fps=44100, nbytes=2):
self.filename = filename
self.nbytes = nbytes
+ self.bufsize=bufsize
self.fps = fps
self.f = 's%dle'%(8*nbytes)
self.acodec = 'pcm_s%dle'%(8*nbytes)
@@ -34,7 +30,13 @@ class FFMPEG_AudioReader:
'-acodec', self.acodec,
'-ar', "%d"%self.fps,
'-ac', '%d'%self.nchannels, '-']
- self.proc = sp.Popen( cmd, stdin=sp.PIPE,
+
+ if hasattr(self, 'proc'):
+ self.proc.kill()
+ del self.proc
+
+ self.proc = sp.Popen( cmd, bufsize=self.bufsize,
+ stdin=sp.PIPE,
stdout=sp.PIPE,
stderr=sp.PIPE)
self.pos = 1
@@ -49,10 +51,11 @@ class FFMPEG_AudioReader:
stderr=sp.PIPE)
proc.stdout.readline()
proc.terminate()
- infos = proc.stderr.read()
+ infos = proc.stderr.read().decode('utf8')
+
if print_infos:
# print the whole info text returned by FFMPEG
- print infos
+ print( infos )
lines = infos.splitlines()
@@ -129,8 +132,13 @@ class FFMPEG_AudioReader:
class WaveReader:
+ """ DEPRECATED - Do not use if you can avoid. """
def __init__(self, filename):
+
+ import os
+ from moviepy.Clip import Clip
+
if not filename.endswith('.wav'):
name, ext = os.path.splitext(os.path.basename(filename))
if temp_wav is None:
diff --git a/moviepy/conf.py b/moviepy/conf.py
index a9faf319..ecf8e59a 100644
--- a/moviepy/conf.py
+++ b/moviepy/conf.py
@@ -41,8 +41,8 @@ if FFMPEG_BINARY is None:
if __name__ == "__main__":
if tryffmpeg(FFMPEG_BINARY):
- print "MoviePy : ffmpeg successfully found."
+ print( "MoviePy : ffmpeg successfully found." )
else:
- print "MoviePy : can't find ffmpeg."
+ print( "MoviePy : can't find ffmpeg." )
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index f823b60a..1033c156 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -12,6 +12,7 @@ import subprocess
import multiprocessing
import threading
from copy import copy
+from tqdm import tqdm
import numpy as np
@@ -112,18 +113,18 @@ class VideoClip(Clip):
once parallelization is implemented.
"""
- print "writing frames in [%s]" % foldername,
+ print( "writing frames in [%s]" % foldername )
try:
os.mkdir(foldername)
except:
if not overwrite:
- print "Error: Maybe set overwrite =true "
+ 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:]:
+ for i, t in tqdm(list(enumerate(tt))[startFrame:]):
picname = "%s/%s%06d.png" % (foldername, foldername, i)
pic = self.get_frame(t)
@@ -131,10 +132,8 @@ class VideoClip(Clip):
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."
+ print( "done." )
return DirectoryClip(foldername, fps=fps)
@@ -375,7 +374,7 @@ class VideoClip(Clip):
"""
def verboseprint(s):
- if verbose: print "MoviePy: " + s
+ if verbose: print( "MoviePy: " + s )
if fps is None:
fps = self.fps
@@ -416,7 +415,7 @@ class VideoClip(Clip):
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
proc.wait()
- print proc.stderr
+ print( proc.stderr )
for f in tempfiles:
os.remove(f)
@@ -442,7 +441,7 @@ class VideoClip(Clip):
center = self.subclip(ta, tb).fx(**kwargs)
right = None if (tb is None) else self.subclip(ta=tb)
- clips = [c for c in left, center, right if c != None]
+ clips = [c for c in [left, center, right] if c != None]
cc = VideoClip.concat(clips)
if self.start != None:
@@ -478,7 +477,8 @@ class VideoClip(Clip):
lambda t: np.ones(self.get_frame(t).shape))
return self.set_mask(mask.set_duration(self.duration))
- def on_color(self, size=None, color=(0, 0, 0), pos=None, col_opacity=None):
+ 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 a possibly bigger size. Can serve to flatten transparent
@@ -498,11 +498,13 @@ class VideoClip(Clip):
colorclip = ColorClip(size, color)
if col_opacity:
colorclip = colorclip.set_opacity(col_opacity)
+
+ if self.duration != None:
+ colorclip = colorclip.set_duration(self.duration)
result = CompositeVideoClip([colorclip, self.set_pos(pos)],
transparent=(col_opacity != None))
- if hasattr(self,'duration'):
- result.duration = self.duration
+
return result
@@ -812,7 +814,7 @@ class TextClip(ImageClip):
"""
def __init__(self, txt, size=None, color='black', bg_color='transparent',
- fontsize=None, font='Times-New-Roman-Regular',
+ fontsize=None, font='Courier',
stroke_color=None, stroke_width=1, method='label',
kerning=None, align='center', interline=None,
tempfile='temp.png',
@@ -854,7 +856,7 @@ class TextClip(ImageClip):
"-type", "truecolormatte", "PNG32:%s"%tempfile]
if print_cmd:
- print " ".join(cmd)
+ print( " ".join(cmd) )
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
proc.wait()
diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.py
index aa9f179a..2a314fdf 100644
--- a/moviepy/video/compositing/CompositeVideoClip.py
+++ b/moviepy/video/compositing/CompositeVideoClip.py
@@ -66,7 +66,8 @@ class CompositeVideoClip(VideoClip):
# compute mask
if transparent:
- maskclips = [c.mask.set_pos(c.pos) for c in self.clips]
+ maskclips = [c.mask.set_pos(c.pos) for c in self.clips
+ if c.mask is not None]
self.mask = CompositeVideoClip(maskclips,self.size,
transparent=False, ismask=True)
@@ -89,29 +90,34 @@ class CompositeVideoClip(VideoClip):
def clips_array(array, rows_widths=None, cols_widths=None,
- transparent = True, bg_color = (0,0,0)):
+ transparent = False, bg_color = (0,0,0)):
array = np.array(array)
- sizes_array = np.vectorize(lambda c:c.size)(array)
+ sizes_array = np.array([[c.size for c in line] for line in array])
+
if rows_widths == None:
- rows_widths = sizes_array.max(axis=0)
+ rows_widths = sizes_array[:,:,1].max(axis=1)
if cols_widths == None:
- cols_widths = sizes_array.max(axis=1)
+ cols_widths = sizes_array[:,:,0].max(axis=0)
- xx = np.cumsum([0]+list(cols_width))
- yy = np.cumsum([0]+list(rows_width))
+ xx = np.cumsum([0]+list(cols_widths))
+ yy = np.cumsum([0]+list(rows_widths))
- for j,(x,rw) in enumerate(zip(xx,cols_width)):
- for i,(y,cw) in enumerate(zip(yy,cols_width)):
+ for j,(x,cw) in list(enumerate(zip(xx[:-1],cols_widths))):
+ for i,(y,rw) in list(enumerate(zip(yy[:-1],rows_widths))):
clip = array[i,j]
w,h = clip.size
if (w < cw) or (h < rw):
- clip = CompositeClip([clip], size = (cw,rw),
- transparent = True, bg_color = (0,0,0))
- array[i,j] = clip.set_pos((x,y))
-
+ clip = (CompositeVideoClip([clip.set_pos('center')],
+ size = (cw,rw),
+ transparent = transparent,
+ bg_color = (bg_color)).
+ set_duration(clip.duration))
+
+ array[i,j] = clip.set_pos((x,y))
- return CompositeVideoClip(array.flatten(),
- size = (xx[-1],yy[-1]))
+ return CompositeVideoClip(array.flatten(), size = (xx[-1],yy[-1]),
+ transparent=transparent,
+ bg_color = bg_color)
diff --git a/moviepy/video/compositing/concatenate.py b/moviepy/video/compositing/concatenate.py
index b3fb3423..013fc5dd 100644
--- a/moviepy/video/compositing/concatenate.py
+++ b/moviepy/video/compositing/concatenate.py
@@ -75,8 +75,8 @@ def concatenate(clipslist, method = 'chain', transition=None,
# add a mask to the clips which have none
clips_withmask = [(c if (c.mask!=None) else c.add_mask())
for c in clipslist]
- result.mask = ConcatVideoClip([c.mask for c in clips_withmask],
- bg_color=0, ismask=True)
+ result.mask = concatenate([c.mask for c in clips_withmask],
+ bg_color=0, ismask=True, transparent=False)
# Compute the audio, if any.
diff --git a/moviepy/video/fx/__init__.py b/moviepy/video/fx/__init__.py
index 38b6baba..2d8c3638 100644
--- a/moviepy/video/fx/__init__.py
+++ b/moviepy/video/fx/__init__.py
@@ -11,4 +11,4 @@ fx_list = [f for f in files if ( f.endswith('.py') and not f.startswith('_'))]
__all__ = [c[:-3] for c in fx_list]
for name in __all__:
- exec("from %s import %s"%(name,name))
+ exec("from .%s import %s"%(name,name))
diff --git a/moviepy/video/fx/crop.py b/moviepy/video/fx/crop.py
index cf95c19e..35d5748e 100644
--- a/moviepy/video/fx/crop.py
+++ b/moviepy/video/fx/crop.py
@@ -1,5 +1,12 @@
def crop(clip, x1=None, y1=None, x2=None, y2=None,
- width = None, height=None, x_center= None, y_center=None):
+ width = None, height=None,
+ x_center= None, y_center=None):
+ """
+ >>> crop(clip, x1,y1,x2,y2) # defines the rectangle of the crop
+ >>> crop(clip, x1=10, width=200)
+
+
+ """
if width:
diff --git a/moviepy/video/fx/resize.py b/moviepy/video/fx/resize.py
index 10d2130f..4e05efab 100644
--- a/moviepy/video/fx/resize.py
+++ b/moviepy/video/fx/resize.py
@@ -16,7 +16,11 @@ except ImportError:
def resizer(pic, newsize):
newsize = map(int, newsize)[::-1]
shape = pic.shape
- newshape = (newsize[0],newsize[1],shape[2])
+ if len(shape)==3:
+ newshape = (newsize[0],newsize[1], shape[2] )
+ else:
+ newshape = (newsize[0],newsize[1])
+
pilim = Image.fromarray(pic)
resized_pil = pilim.resize(newsize[::-1], Image.ANTIALIAS)
arr = np.fromstring(resized_pil.tostring(), dtype='uint8')
diff --git a/moviepy/video/io/VideoFileClip.py b/moviepy/video/io/VideoFileClip.py
index 3879bd5d..7fc9b614 100644
--- a/moviepy/video/io/VideoFileClip.py
+++ b/moviepy/video/io/VideoFileClip.py
@@ -55,16 +55,10 @@ class VideoFileClip(VideoClip):
# Make a reader for the audio, if any.
if audio:
- try:
- self.audio = AudioFileClip(filename,
- buffersize= audio_buffersize,
- fps = audio_fps,
- nbytes = audio_nbytes)
- except:
- if verbose:
- print "No audio found in %s"%filename
- pass
-
+ self.audio = AudioFileClip(filename,
+ buffersize= audio_buffersize,
+ fps = audio_fps,
+ nbytes = audio_nbytes)
def coreader(self, audio=True):
""" Returns a copy of the AudioFileClip, i.e. a new entrance point
diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.py
index e6531862..90c0baed 100644
--- a/moviepy/video/io/ffmpeg_reader.py
+++ b/moviepy/video/io/ffmpeg_reader.py
@@ -1,3 +1,5 @@
+from __future__ import division
+
import subprocess as sp
import re
@@ -8,16 +10,25 @@ from moviepy.tools import cvsecs
class FFMPEG_VideoReader:
- def __init__(self, filename, print_infos=False, pix_fmt="rgb24"):
+ def __init__(self, filename, print_infos=False, bufsize = None,
+ pix_fmt="rgb24"):
self.filename = filename
+ self.load_infos(print_infos)
self.pix_fmt = pix_fmt
- self.initialize()
if pix_fmt == 'rgba':
self.depth = 4
else:
self.depth = 3
- self.load_infos(print_infos)
+
+ if bufsize is None:
+ w, h = self.size
+ bufsize = self.depth * w * h +100
+
+ self.bufsize= bufsize
+ self.initialize()
+
+
self.pos = 1
self.lastread = self.read_frame()
@@ -28,7 +39,11 @@ class FFMPEG_VideoReader:
'-f', 'image2pipe',
"-pix_fmt", self.pix_fmt,
'-vcodec', 'rawvideo', '-']
- self.proc = sp.Popen(cmd, stdin=sp.PIPE,
+ if hasattr(self,'proc'):
+ self.proc.kill()
+ del self.proc
+ self.proc = sp.Popen(cmd, bufsize= self.bufsize,
+ stdin=sp.PIPE,
stdout=sp.PIPE,
stderr=sp.PIPE)
@@ -42,10 +57,10 @@ class FFMPEG_VideoReader:
stderr=sp.PIPE)
proc.stdout.readline()
proc.terminate()
- infos = proc.stderr.read()
+ infos = proc.stderr.read().decode('utf8')
if print_infos:
# print the whole info text returned by FFMPEG
- print infos
+ print( infos )
lines = infos.splitlines()
if "No such file or directory" in lines[-1]:
@@ -56,7 +71,7 @@ class FFMPEG_VideoReader:
# get the size, of the form 460x320 (w x h)
match = re.search(" [0-9]*x[0-9]*(,| )", line)
- self.size = map(int, line[match.start():match.end()-1].split('x'))
+ self.size = list(map(int, line[match.start():match.end()-1].split('x')))
# get the frame rate
match = re.search("( [0-9]*.| )[0-9]* (tbr|fps)", line)
@@ -83,20 +98,23 @@ class FFMPEG_VideoReader:
self.proc.stdout.flush()
self.pos += n
+
def read_frame(self):
w, h = self.size
try:
# Normally, the readr should not read after the last frame...
# if it does, raise an error.
- s = self.proc.stdout.read(self.depth*w*h)
+ nbytes= self.depth*w*h
+ s = self.proc.stdout.read(nbytes)
+ assert len(s) == nbytes
result = np.fromstring(s,
- dtype='uint8').reshape((h, w, len(s)/(w*h)))
+ dtype='uint8').reshape((h, w, len(s)//(w*h)))
self.proc.stdout.flush()
- except:
+ except IOError:
self.proc.terminate()
serr = self.proc.stderr.read()
- print "error: string: %s, stderr: %s" % (s, serr)
- raise
+ print( "error: string: %s, stderr: %s" % (s, serr))
+ raise IOError
self.lastread = result
diff --git a/moviepy/video/io/ffmpeg_tools.py b/moviepy/video/io/ffmpeg_tools.py
index 3c5479ce..a8a2f14b 100644
--- a/moviepy/video/io/ffmpeg_tools.py
+++ b/moviepy/video/io/ffmpeg_tools.py
@@ -20,9 +20,9 @@ def subprocess_call(f, *a, **k):
proc.wait()
if proc.returncode:
sys.stdout.write( "\nWARNING: this command returned an error:")
- sys.stdout.write(proc.stderr.read())
+ sys.stdout.write(proc.stderr.read().decode('utf8'))
else:
- sys.stdout.write( "\n... ffmpeg command successful.\n")
+ sys.stdout.write( "\n... ffmpeg command successful.\n")
sys.stdout.flush()
@subprocess_call
diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.py
index b2a701a3..f5f71c91 100644
--- a/moviepy/video/io/ffmpeg_writer.py
+++ b/moviepy/video/io/ffmpeg_writer.py
@@ -59,8 +59,8 @@ class FFMPEG_VideoWriter:
stderr=sp.PIPE)
def write_frame(self,img_array):
- #self.proc.stdin.write(img_array.tostring())
- img_array.tofile(self.proc.stdin)
+ self.proc.stdin.write(img_array.tostring())
+ #img_array.tofile(self.proc.stdin) only python 2.7
def close(self):
self.proc.stdin.close()
diff --git a/moviepy/video/tools/drawing.py b/moviepy/video/tools/drawing.py
index 09cddfa3..1f10277a 100644
--- a/moviepy/video/tools/drawing.py
+++ b/moviepy/video/tools/drawing.py
@@ -195,20 +195,19 @@ def color_split(size,x=None,y=None,p1=None,p2=None,vector=None,
w,h = size
shape = (h, w) if np.isscalar(col1) else (h, w, len(col1))
arr = np.zeros(shape)
- print shape
if x:
arr[:,:x] = col1
arr[:,x:] = col2
elif y:
arr[:y] = col1
arr[y:] = col2
+
+ return arr
# if we are here, it means we didn't exit with a proper 'return'
- print "Arguments in color_plit not understood !"
+ print( "Arguments in color_split not understood !" )
raise
-# to come: circles, squares, rectangles
-
def circle(screensize, center, radius, col1=1.0, col2=0, blur=1):
"""
Draws a circle of color ``col1``, on a background of color ``col2``,