Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
Classes for advantageous handling of static clips.
ImageClip, ColorClip, TextClip
"""
import subprocess
import os
import numpy as np
import moviepy.video.VideoClip as VC
import moviepy.video.io.readers as readers
class ImageClip(VC.VideoClip):
"""
A video clip originating from a picture. This clip will simply
display the given picture at all times. For instance:
>>> clip = ImageClip("myHouse.jpeg")
>>> clip = ImageClip( someArray ) # a Numpy array represent
:param img: Any picture file (png, tiff, jpeg, etc.) or any array
representing an RGB image (for instance a frame from a VideoClip
or a picture read with scipy of skimage's imread method).
:param ismask: `True` if the clip is a mask.
:param transparent: `True` (default) if you want the alpha layer
of the picture (if it exists) to be used as a mask.
def __init__(self, sequence, fps=None, durations=None, with_mask=True,
ismask=False, load_images=False):
# CODE WRITTEN AS IT CAME, MAY BE IMPROVED IN THE FUTURE
if (fps is None) and (durations is None):
raise ValueError("Please provide either 'fps' or 'durations'.")
VideoClip.__init__(self, ismask=ismask)
# Parse the data
fromfiles = True
if isinstance(sequence, list):
if isinstance(sequence[0], str):
if load_images:
sequence = [imread(f) for f in sequence]
fromfiles = False
else:
fromfiles= True
else:
# sequence is already a list of numpy arrays
fromfiles = False
else:
def __init__(self, img, ismask=False, transparent=True, fromalpha=False):
VC.VideoClip.__init__(self, ismask=ismask)
if isinstance(img, str):
img = readers.read_image(img,with_mask=transparent)
if len(img.shape) == 3: # img is (now) a RGB(a) numpy array
if img.shape[2] == 4:
if fromalpha:
img = 1.0 * img[:, :, 3] / 255
elif ismask:
img = 1.0 * img[:, :, 0] / 255
elif transparent:
self.mask = ImageClip(
1.0 * img[:, :, 3] / 255, ismask=True)
img = img[:, :, :3]
elif ismask:
def __init__(self, foldername, fps, withmask=True, ismask=False):
VideoClip.__init__(self, ismask=ismask)
self.directory = foldername
self.fps = fps
self.imagefiles = sorted(os.listdir(foldername))
self.duration = 1.0* len(self.imagefiles) / self.fps
self.end = self.duration
self.lastpos = None
self.lastimage = None
def get_frame(t):
pos = int(self.fps*t)
def fl(self, fl, applyto=[], keep_duration=True):
"""
Equivalent to VideoClip.fl . The result is no more an
ImageClip, it has the class VideoClip (as it may be animated)
"""
# When we use fl on an image clip it may become animated.
#Therefore the result is not an ImageClip, just a VideoClip.
newclip = VC.VideoClip.fl(self,fl, applyto=applyto,
keep_duration=keep_duration)
newclip.__class__ = VC.VideoClip
return newclip
for attr in apply_to:
if hasattr(self, attr):
a = getattr(self, attr)
if a is not None:
new_a = a.fl_time(time_func)
setattr(self, attr, new_a)
# ##
#
# The old functions to_videofile, to_gif, to_images sequences have been
# replaced by the more explicite write_videofile, write_gif, etc.
VideoClip.set_pos = deprecated_version_of(VideoClip.set_position,
'set_pos')
VideoClip.to_videofile = deprecated_version_of(VideoClip.write_videofile,
'to_videofile')
VideoClip.to_gif = deprecated_version_of(VideoClip.write_gif, 'to_gif')
VideoClip.to_images_sequence = deprecated_version_of(VideoClip.write_images_sequence,
'to_images_sequence')
class ColorClip(ImageClip):
"""An ImageClip showing just one color.
Parameters
-----------
size
Size (width, height) in pixels of the clip.
color
# encoding: utf-8
#
# © 2017 Benjamin Mintz
# https://bmintz.mit-license.org/@2017
#
"""
techmeme.py: CLI app to turn videos into dank technical may-mays
"""
import moviepy.video.VideoClip
from config import TechnicalMemeConfig
class TechnicalMeme(moviepy.video.VideoClip.VideoClip):
def __init__(self, *, source_filename, config):
self.source_filename = source_filename
self.config = config
# Add methods preview and show (only if pygame installed)
try:
from moviepy.video.io.preview import show, preview
except ImportError:
def preview(self, *args, **kwargs):
"""NOT AVAILABLE : clip.preview requires Pygame installed."""
raise ImportError("clip.preview requires Pygame installed")
def show(self, *args, **kwargs):
"""NOT AVAILABLE : clip.show requires Pygame installed."""
raise ImportError("clip.show requires Pygame installed")
VideoClip.preview = preview
VideoClip.show = show
try:
from moviepy.audio.io.preview import preview
except ImportError:
def preview(self, *args, **kwargs):
""" NOT AVAILABLE : clip.preview requires Pygame installed."""
raise ImportError("clip.preview requires Pygame installed")
AudioClip.preview = preview
h = max([r[1] for r in sizes])
tt = np.maximum(0, tt + padding*np.arange(len(tt)))
if method == "chain":
def make_frame(t):
i = max([i for i, e in enumerate(tt) if e <= t])
return clips[i].get_frame(t - tt[i])
def get_mask(c):
mask = c.mask or ColorClip([1, 1], color=1, ismask=True)
if mask.duration is None:
mask.duration = c.duration
return mask
result = VideoClip(ismask = ismask, make_frame = make_frame)
if any([c.mask is not None for c in clips]):
masks = [get_mask(c) for c in clips]
result.mask = concatenate_videoclips(masks, method="chain",
ismask=True)
result.clips = clips
elif method == "compose":
result = CompositeVideoClip( [c.set_start(t).set_position('center')
for (c, t) in zip(clips, tt)],
size = (w, h), bg_color=bg_color, ismask=ismask)
else:
raise Exception("Moviepy Error: The 'method' argument of "
"concatenate_videoclips must be 'chain' or 'compose'")
result.tt = tt
result.start_times = tt[:-1]
def add_mask(self):
"""Add a mask VideoClip to the VideoClip.
Returns a copy of the clip with a completely opaque mask
(made of ones). This makes computations slower compared to
having a None mask but can be useful in many cases. Choose
Set ``constant_size`` to `False` for clips with moving
image size.
"""
if self.has_constant_size:
mask = ColorClip(self.size, 1.0, ismask=True)
return self.set_mask(mask.set_duration(self.duration))
else:
make_frame = lambda t: np.ones(self.get_frame(t).shape[:2], dtype=float)
mask = VideoClip(ismask=True, make_frame=make_frame)
return self.set_mask(mask.set_duration(self.duration))