Skip to content

Video editing with Python

fixed "clip leak" bug, fixed opencv resize, changed messages/warnings

Zulko4ed39601116f
diff --git a/docs/getting_started/effects.rst b/docs/getting_started/effects.rst
index 3b1606e1..d548dda6 100644
--- a/docs/getting_started/effects.rst
+++ b/docs/getting_started/effects.rst
@@ -30,9 +30,6 @@ Most of the time when the times are not provided they are guessed, for instance
Methods to change the clip attributes
---------------------------------------
-
-
-
clip.fx
----------
diff --git a/moviepy/audio/io/AudioFileClip.py b/moviepy/audio/io/AudioFileClip.py
index 0518e78c..6054d898 100644
--- a/moviepy/audio/io/AudioFileClip.py
+++ b/moviepy/audio/io/AudioFileClip.py
@@ -59,15 +59,17 @@ class AudioFileClip(AudioClip):
AudioClip.__init__(self)
self.filename = filename
- self.reader = FFMPEG_AudioReader(filename,fps=fps,nbytes=nbytes,
+ reader = FFMPEG_AudioReader(filename,fps=fps,nbytes=nbytes,
buffersize=buffersize)
+
+ self.reader = reader
self.fps = fps
- self.duration = self.reader.duration
- self.end = self.duration
+ self.duration = reader.duration
+ self.end = reader.duration
- self.make_frame = lambda t: self.reader.get_frame(t)
- self.nchannels = self.reader.nchannels
+ self.make_frame = lambda t: reader.get_frame(t)
+ self.nchannels = reader.nchannels
def coreader(self):
diff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.py
index 032aee52..e895f5d8 100644
--- a/moviepy/audio/io/ffmpeg_audiowriter.py
+++ b/moviepy/audio/io/ffmpeg_audiowriter.py
@@ -147,7 +147,7 @@ def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
else:
logfile = None
- verbose_print(verbose, "Writing audio in %s\n"%filename)
+ verbose_print(verbose, "[MoviePy] Writing audio in %s\n"%filename)
writer = FFMPEG_AudioWriter(filename, fps, nbytes, clip.nchannels,
codec=codec, bitrate=bitrate,
@@ -181,4 +181,4 @@ def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
if write_logfile:
logfile.close()
- verbose_print(verbose, "Done writing Audio in %s !\n"%filename)
+ verbose_print(verbose, "[MoviePy] Done.\n")
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index 4bc07058..fded73c0 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -311,13 +311,12 @@ class VideoClip(Clip):
"temp_audiofile with the right extension in write_videofile.")
audiofile = (name + Clip._TEMP_FILES_PREFIX +
- "write_videofile_SOUND.%s" % audio_ext)
+ "wvf_snd.%s" % audio_ext)
# enough cpu for multiprocessing ? USELESS RIGHT NOW, WILL COME AGAIN
# enough_cpu = (multiprocessing.cpu_count() > 1)
- verbose_print(verbose, "\nMoviePy: building video file %s\n" % filename
- + 40 * "-" + "\n")
+ verbose_print(verbose, "[MoviePy] >>>> Building video %s\n" % filename)
if make_audio:
self.audio.write_audiofile(audiofile, audio_fps,
@@ -337,7 +336,7 @@ class VideoClip(Clip):
if remove_temp and make_audio:
os.remove(audiofile)
- verbose_print(verbose, "\nYour video is ready !\n")
+ verbose_print(verbose, "[MoviePy] >>>> Video ready: %s \n\n"%filename)
@requires_duration
@@ -383,7 +382,7 @@ class VideoClip(Clip):
"""
- verbose_print(verbose, "MoviePy: Writing frames %s." % (nameformat))
+ verbose_print(verbose, "[MoviePy] Writing frames %s." % (nameformat))
tt = np.arange(0, self.duration, 1.0 / fps)
@@ -395,7 +394,7 @@ class VideoClip(Clip):
self.save_frame(name, t, withmask=withmask)
verbose_print(verbose,
- "MoviePy: Done writing frames %s." % (nameformat))
+ "[MoviePy]: Done writing frames %s.\n\n" % (nameformat))
return filenames
@@ -776,6 +775,60 @@ class VideoClip(Clip):
self.audio = self.audio.fx(fun, *a, **k)
+
+
+
+
+class UpdatedVideoClip(VideoClip):
+ """
+
+ Class of clips whose make_frame requires some objects to
+ be updated. Particularly practical in science where some
+ algorithm needs to make some steps before a new frame can
+ be generated.
+
+ UpdatedVideoClips have the following make_frame:
+
+ >>> def make_frame(t):
+ >>> while self.world.clip_t < t:
+ >>> world.update() # updates, and increases world.clip_t
+ >>> return world.to_frame()
+
+ Parameters
+ -----------
+
+ world
+ An object with the following attributes:
+ - world.clip_t : the clip's time corresponding to the
+ world's state
+ - world.update() : update the world's state, (including
+ increasing world.clip_t of one time step)
+ - world.to_frame() : renders a frame depending on the world's state
+
+ ismask
+ True if the clip is a WxH mask with values in 0-1
+
+ duration
+ Duration of the clip, in seconds
+
+ """
+
+
+ def __init__(self, world, ismask=False, duration=None):
+
+ self.world = world
+ def make_frame(t):
+ while self.world.clip_t < t:
+ world.update()
+ return world.to_frame()
+ VideoClip.__init__(self, make_frame= make_frame,
+ ismask=ismask, duration=duration)
+
+
+
+
+
+
"""---------------------------------------------------------------------
ImageClip (base class for all 'static clips') and its subclasses
@@ -1124,4 +1177,4 @@ class TextClip(ImageClip):
"""
string = string.lower()
names_list = TextClip.list(arg)
- return [name for name in names_list if string in name.lower()]
+ return [name for name in names_list if string in name.lower()]
\ No newline at end of file
diff --git a/moviepy/video/fx/make_loopable.py b/moviepy/video/fx/make_loopable.py
index a7162ba4..131f39a8 100644
--- a/moviepy/video/fx/make_loopable.py
+++ b/moviepy/video/fx/make_loopable.py
@@ -1,4 +1,5 @@
import moviepy.video.compositing.transitions as transfx
+from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
def make_loopable(clip, cross):
"""
diff --git a/moviepy/video/fx/resize.py b/moviepy/video/fx/resize.py
index 60b6d2ef..27d11af2 100644
--- a/moviepy/video/fx/resize.py
+++ b/moviepy/video/fx/resize.py
@@ -2,10 +2,14 @@ resize_possible = True
try:
# TRY USING OpenCV AS RESIZER
+ #raise ImportError #debugging
import cv2
- resizer = lambda pic, newsize : cv2.resize(pic.astype('uint8'),
- tuple(map(int, newsize)),
- interpolation=cv2.INTER_AREA)
+ import numpy as np
+ def resizer (pic, newsize):
+ lx, ly = int(newsize[0]), int(newsize[1])
+ return cv2.resize(+pic.astype('uint8'), (lx, ly),
+ interpolation=cv2.INTER_AREA)
+
resizer.origin = "cv2"
except ImportError:
diff --git a/moviepy/video/io/VideoFileClip.py b/moviepy/video/io/VideoFileClip.py
index 0cf2425e..4bb3a3c1 100644
--- a/moviepy/video/io/VideoFileClip.py
+++ b/moviepy/video/io/VideoFileClip.py
@@ -52,8 +52,8 @@ class VideoFileClip(VideoClip):
# Make a reader
pix_fmt= "rgba" if has_mask else "rgb24"
- self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
-
+ reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)
+ self.reader = reader
# Make some of the reader's attributes accessible from the clip
self.duration = self.reader.duration
self.end = self.reader.duration
@@ -63,15 +63,15 @@ class VideoFileClip(VideoClip):
if has_mask:
- self.make_frame = lambda t: self.reader.get_frame(t)[:,:,:3]
- mask_mf = lambda t: self.reader.get_frame(t)[:,:,3]/255.0
+ self.make_frame = lambda t: reader.get_frame(t)[:,:,:3]
+ mask_mf = lambda t: reader.get_frame(t)[:,:,3]/255.0
self.mask = (VideoClip(ismask = True, make_frame = mask_mf)
.set_duration(self.duration))
self.mask.fps = self.fps
else:
- self.make_frame = lambda t: self.reader.get_frame(t)
+ self.make_frame = lambda t: reader.get_frame(t)
# Make a reader for the audio, if any.
if audio and self.reader.infos['audio_found']:
diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.py
index 0c885bb8..acb64d11 100644
--- a/moviepy/video/io/ffmpeg_reader.py
+++ b/moviepy/video/io/ffmpeg_reader.py
@@ -7,6 +7,10 @@ from __future__ import division
import subprocess as sp
import re
+import warnings
+import logging
+logging.captureWarnings(True)
+
import numpy as np
from moviepy.config import get_setting # ffmpeg, ffmpeg.exe, etc...
@@ -102,13 +106,14 @@ class FFMPEG_VideoReader:
s = self.proc.stdout.read(nbytes)
if len(s) != nbytes:
- print( "Warning: in file %s, "%(self.filename)+
+ warnings.warn("Warning: in file %s, "%(self.filename)+
"%d bytes wanted but %d bytes read,"%(nbytes, len(s))+
"at frame %d/%d, at time %.02f/%.02f sec. "%(
self.pos,self.nframes,
1.0*self.pos/self.fps,
self.duration)+
- "Using the last valid frame instead.")
+ "Using the last valid frame instead.",
+ UserWarning)
if not hasattr(self, 'lastread'):
raise IOError(("MoviePy error: failed to read the first frame of "
diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.py
index 5156a346..1dcd2220 100644
--- a/moviepy/video/io/ffmpeg_writer.py
+++ b/moviepy/video/io/ffmpeg_writer.py
@@ -190,7 +190,7 @@ def ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,
else:
logfile = None
- verbose_print(verbose, "\nWriting video into %s\n"%filename)
+ verbose_print(verbose, "[MoviePy] Writing video %s\n"%filename)
writer = FFMPEG_VideoWriter(filename, clip.size, fps, codec = codec,
preset=preset, bitrate=bitrate, logfile=logfile,
audiofile=audiofile, threads=threads,
@@ -213,7 +213,7 @@ def ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,
if write_logfile:
logfile.close()
- verbose_print(verbose, "Done writing video in %s !" % filename)
+ verbose_print(verbose, "[MoviePy] Done.\n")
def ffmpeg_write_image(filename, image, logfile=False):
@@ -245,7 +245,7 @@ def ffmpeg_write_image(filename, image, logfile=False):
out, err = proc.communicate(image.tostring())
if proc.returncode:
- err = "\n".join(["MoviePy running : %s" % cmd,
+ err = "\n".join(["[MoviePy] Running : %s\n" % cmd,
"WARNING: this command returned an error:",
err.decode('utf8')])
raise IOError(err)
diff --git a/moviepy/video/io/gif_writers.py b/moviepy/video/io/gif_writers.py
index 4bc3d058..1fb49038 100644
--- a/moviepy/video/io/gif_writers.py
+++ b/moviepy/video/io/gif_writers.py
@@ -32,10 +32,10 @@ def write_gif_with_tempfiles(clip, filename, fps=None, program= 'ImageMagick',
tempfiles = []
- verbose_print(verbose, "\nMoviePy: building GIF file %s\n"%filename
+ verbose_print(verbose, "\n[MoviePy] Building file %s\n"%filename
+40*"-"+"\n")
- verbose_print(verbose, "Generating GIF frames.\n")
+ verbose_print(verbose, "[MoviePy] Generating GIF frames...\n")
total = int(clip.duration*fps)+1
for i, t in tqdm(enumerate(tt), total=total):
@@ -44,12 +44,10 @@ def write_gif_with_tempfiles(clip, filename, fps=None, program= 'ImageMagick',
tempfiles.append(name)
clip.save_frame(name, t, savemask=True)
- verbose_print(verbose, "Done generating GIF frames.\n")
-
delay = int(100.0/fps)
if program == "ImageMagick":
-
+ verbose_print(verbose, "[MoviePy] Optimizing GIF with ImageMagick... ")
cmd = [get_setting("IMAGEMAGICK_BINARY"),
'-delay' , '%d'%delay,
"-dispose" ,"%d"%(2 if dispose else 1),
@@ -71,6 +69,7 @@ def write_gif_with_tempfiles(clip, filename, fps=None, program= 'ImageMagick',
try:
subprocess_call( cmd, verbose = verbose )
+ verbose_print(verbose, "[MoviePy] GIF %s is ready."%filename)
except (IOError,OSError) as err:
@@ -209,19 +208,17 @@ def write_gif(clip, filename, fps=None, program= 'ImageMagick',
proc3 = sp.Popen(cmd3, **popen_params)
# We send all the frames to the first process
- verbose_print(verbose, "\nMoviePy: building GIF file %s\n"%filename
- +40*"-"+"\n")
- verbose_print(verbose, "Generating GIF frames...\n")
+ verbose_print(verbose, "\n[MoviePy] >>>> Building file %s\n"%filename)
+ verbose_print(verbose, "[MoviePy] Generating GIF frames...\n")
try:
for frame in clip.iter_frames(fps=fps, progress_bar=True):
proc1.stdin.write(frame.tostring())
- verbose_print(verbose, "Done.\n")
except IOError as err:
- error = ("MoviePy Error: creation of %s failed because "
+ error = ("[MoviePy] Error: creation of %s failed because "
"of the following error:\n\n%s.\n\n."%(filename, str(err)))
if program == "ImageMagick":
@@ -231,11 +228,12 @@ def write_gif(clip, filename, fps=None, program= 'ImageMagick',
"path to the ImageMagick binary in file conf.py." )
raise IOError(error)
- verbose_print(verbose, "Writing GIF... ")
+ if program == 'ImageMagick':
+ verbose_print(verbose, "[MoviePy] Optimizing the GIF with ImageMagick...\n")
proc1.stdin.close()
proc1.wait()
if program == 'ImageMagick':
proc2.wait()
if opt:
proc3.wait()
- verbose_print(verbose, 'Done. Your GIF is ready !')
\ No newline at end of file
+ verbose_print(verbose, "[MoviePy] >>>> File %s is ready !"%filename)
\ No newline at end of file
diff --git a/moviepy/video/io/html_tools.py b/moviepy/video/io/html_tools.py
index 6295c2c9..00817a03 100644
--- a/moviepy/video/io/html_tools.py
+++ b/moviepy/video/io/html_tools.py
@@ -19,24 +19,28 @@ from moviepy.audio.AudioClip import AudioClip
try:
from IPython.display import HTML
ipython_available = True
+ class HTML2(HTML):
+ def __add__(self, other):
+ return HTML2(self.data+other.data)
+
except ImportError:
ipython_available = False
from .ffmpeg_reader import ffmpeg_parse_infos
sorry = "Sorry, seems like your browser doesn't support HTML5 audio/video"
-templates = {"audio":("<center><audio controls>"
+templates = {"audio":("<audio controls>"
"<source %(options)s src='data:audio/%(ext)s;base64,%(data)s'>"
- +sorry+"</audio></center>"),
- "image":"<center><img %(options)s "
- "src='data:image/%(ext)s;base64,%(data)s'></center>",
- "video":("<center><video %(options)s"
+ +sorry+"</audio>"),
+ "image":"<img %(options)s "
+ "src='data:image/%(ext)s;base64,%(data)s'>",
+ "video":("<video %(options)s"
"src='data:video/%(ext)s;base64,%(data)s' controls>"
- +sorry+"</video></center>")}
+ +sorry+"</video>")}
def html_embed(clip, filetype=None, maxduration=60, rd_kwargs=None,
- **html_kwargs):
+ center=True, **html_kwargs):
""" Returns HTML5 code embedding the clip
clip
@@ -77,7 +81,7 @@ def html_embed(clip, filetype=None, maxduration=60, rd_kwargs=None,
"""
if rd_kwargs is None:
- rd_kwargs = {}
+ rd_kwargs = {}
if "Clip" in str(clip.__class__):
TEMP_PREFIX = "__temp__"
@@ -100,7 +104,7 @@ def html_embed(clip, filetype=None, maxduration=60, rd_kwargs=None,
raise ValueError("Unknown class for the clip. Cannot embed and preview.")
return html_embed(filename, maxduration=maxduration, rd_kwargs=rd_kwargs,
- **html_kwargs)
+ center=center, **html_kwargs)
filename = clip
options = " ".join(["%s='%s'"%(str(k), str(v)) for k,v in html_kwargs.items()])
@@ -143,12 +147,15 @@ def html_embed(clip, filetype=None, maxduration=60, rd_kwargs=None,
template = templates[filetype]
- return template%{'data':data, 'options':options, 'ext':ext}
+ result = template%{'data':data, 'options':options, 'ext':ext}
+ if center:
+ result = r"<div align=middle>%s</div>"%result
+ return result
def ipython_display(clip, filetype=None, maxduration=60, t=None, fps=None,
- rd_kwargs=None, **html_kwargs):
+ rd_kwargs=None, center=True, **html_kwargs):
"""
clip
Either the name of a file, or a clip to preview. The clip will
@@ -195,14 +202,18 @@ def ipython_display(clip, filetype=None, maxduration=60, t=None, fps=None,
>>> clip.save_frame("first_frame.jpeg")
>>> mpy.ipython_display("first_frame.jpeg")
"""
-
+
if not ipython_available:
raise ImportError("Only works inside an IPython Notebook")
+ if rd_kwargs is None:
+ rd_kwargs = {}
+
if fps is not None:
rd_kwargs['fps'] = fps
if t is not None:
clip = clip.to_ImageClip(t)
- return HTML(html_embed(clip, filetype=filetype, maxduration=maxduration,
- rd_kwargs=rd_kwargs, **html_kwargs))
\ No newline at end of file
+
+ return HTML2(html_embed(clip, filetype=filetype, maxduration=maxduration,
+ center=center, rd_kwargs=rd_kwargs, **html_kwargs))
\ No newline at end of file
diff --git a/moviepy/video/tools/cuts.py b/moviepy/video/tools/cuts.py
index 97f3ff7f..a56653e9 100644
--- a/moviepy/video/tools/cuts.py
+++ b/moviepy/video/tools/cuts.py
@@ -2,7 +2,6 @@
the cuts in MoviePy """
from moviepy.decorators import use_clip_fps_by_default
-
import numpy as np
@use_clip_fps_by_default
@@ -17,6 +16,119 @@ def find_video_period(clip,fps=None,tmin=.3):
return tt[np.argmax(corrs)]
+class FrameMatch:
+
+ def __init__(self, t1, t2, distance):
+ self.t1, self.t2, self.distance = t1, t2, distance
+ self.time_span = t2-t1
+
+ def __str__(self):
+ return '(%.04f, %.04f, %.04f)'%(self.t1, self.t2, self.time_span)
+
+ def __repr__(self):
+ return '(%.04f, %.04f, %.04f)'%(self.t1, self.t2, self.time_span)
+
+ def __iter__(self):
+ return [self.t1, self.t2, self.distance].__iter__()
+
+
+class FrameMatches(list):
+
+ def __init__(self, lst):
+
+ list.__init__(self, sorted(lst, key=lambda e: e.distance))
+
+ def best(self, n=None, percent=None):
+ if percent is not None:
+ n = len(self)*percent/100
+ return FrameMatches(self[:n])
+
+ def filter(self, fun):
+ return FrameMatches(filter(fun, self))
+
+ def save(self, filename):
+ np.savetxt(np.array(self), matching_frames, fmt='%.03f', delimiter='\t')
+
+ @staticmethod
+ def load(filename):
+ arr = np.loadtxt(filename)
+ mfs = [FrameMatch(*e) for e in arr]
+
+
+
+
+
+def find_matching_frames(clip, dist_thr, max_d, fps=None):
+ """ Returns a list [(t1, t2, distance), ...] for all pairs of frames with
+ (t2-t1 < max_d). Optimized routine. Quite fast.
+
+ clip : a MoviePy video clip, possibly transformed/resized
+ dist_thr: distance above which a match is rejected
+ max_d: maximal duration (in seconds) between two matching frames
+ fps: frames per second (default will be clip.fps)
+ """
+
+ N_pixels = clip.w * clip.h * 3
+ dot_product = lambda F1, F2: (F1*F2).sum()/N_pixels
+ F = {} # will store the frames and their mutual distances
+
+ def distance(t1, t2):
+ uv = dot_product(F[t1]['frame'], F[t2]['frame'])
+ u, v = F[t1]['|F|sq'], F[t2]['|F|sq']
+ return np.sqrt(u+v - 2*uv)
+
+ matching_frames = [] # the final result.
+
+ for (t,frame) in clip.iter_frames(with_times=True, progress_bar=True):
+
+ flat_frame = 1.0*frame.flatten()
+ F_norm_sq = dot_product(flat_frame, flat_frame)
+ F_norm = np.sqrt(F_norm_sq)
+
+ for t2 in F.keys():
+ # forget old frames, add 't' to the others frames
+ # check for early rejections based on differing norms
+ if (t-t2) > max_d:
+ F.pop(t2)
+ else:
+ F[t2][t] = {'min':abs(F[t2]['|F|'] - F_norm),
+ 'max':F[t2]['|F|'] + F_norm}
+ F[t2][t]['rejected']= (F[t2][t]['min'] > dist_thr)
+
+ t_F = sorted(F.keys())
+
+ F[t] = {'frame': flat_frame, '|F|sq': F_norm_sq, '|F|': F_norm}
+
+ for i,t2 in enumerate(t_F):
+ # Compare F(t) to all the previous frames
+
+ if F[t2][t]['rejected']:
+ continue
+
+ dist = distance(t, t2)
+ F[t2][t]['min'] = F[t2][t]['max'] = dist
+ F[t2][t]['rejected'] = (dist >= dist_thr)
+
+ for t3 in t_F[i+1:]:
+ # For all the next times t3, use d(F(t), F(t2)) to
+ # update the bounds on d(F(t), F(t3)). See if you can
+ # conclude on wether F(t) and F(t3) match.
+ t3t, t2t3 = F[t3][t], F[t2][t3]
+ t3t['max'] = min(t3t['max'], dist+ t2t3['max'])
+ t3t['min'] = max(t3t['min'], dist - t2t3['max'],
+ t2t3['min'] - dist)
+
+ if t3t['min'] > dist_thr:
+ t3t['rejected'] = True
+
+ # Store all the good matches (t2,t)
+ matching_frames += [(t1, t, F[t1][t]['min']) for t1 in F
+ if (t1!=t) and not F[t1][t]['rejected']]
+
+ return FrameMatches([FrameMatch(*e) for e in matching_frames])
+
+
+
@use_clip_fps_by_default
def detect_scenes(clip=None, luminosities=None, thr=10,
progress_bar=False, fps=None):