Skip to content

Video editing with Python

Remove dependency to imagemagick by using only imageio for gif and pillow for text clip. Update setup and some test accordingly.

osaajani77dddea56f10
diff --git a/moviepy/config.py b/moviepy/config.py
index 1ba214f1..251a80f3 100644
--- a/moviepy/config.py
+++ b/moviepy/config.py
@@ -19,7 +19,6 @@ except ImportError:
DOTENV = None
FFMPEG_BINARY = os.getenv("FFMPEG_BINARY", "ffmpeg-imageio")
-IMAGEMAGICK_BINARY = os.getenv("IMAGEMAGICK_BINARY", "auto-detect")
IS_POSIX_OS = os.name == "posix"
@@ -57,64 +56,13 @@ else:
f"{err} - The path specified for the ffmpeg binary might be wrong"
)
-if IMAGEMAGICK_BINARY == "auto-detect":
- if os.name == "nt":
- # Try a few different ways of finding the ImageMagick binary on Windows
- try:
- key = wr.OpenKey(wr.HKEY_LOCAL_MACHINE, "SOFTWARE\\ImageMagick\\Current")
- IMAGEMAGICK_BINARY = wr.QueryValueEx(key, "BinPath")[0] + r"\magick.exe"
- key.Close()
- except Exception:
- for imagemagick_filename in ["convert.exe", "magick.exe"]:
- try:
- imagemagick_path = sp.check_output(
- r'dir /B /O-N "C:\\Program Files\\ImageMagick-*"',
- shell=True,
- encoding="utf-8",
- ).split("\n")[0]
- IMAGEMAGICK_BINARY = sp.check_output( # pragma: no cover
- rf'dir /B /S "C:\Program Files\{imagemagick_path}\\'
- f'*{imagemagick_filename}"',
- shell=True,
- encoding="utf-8",
- ).split("\n")[0]
- break
- except Exception:
- IMAGEMAGICK_BINARY = "unset"
-
- if IMAGEMAGICK_BINARY in ["unset", "auto-detect"]:
- if try_cmd(["convert"])[0]:
- IMAGEMAGICK_BINARY = "convert"
- elif not IS_POSIX_OS and try_cmd(["convert.exe"])[0]: # pragma: no cover
- IMAGEMAGICK_BINARY = "convert.exe"
- else: # pragma: no cover
- IMAGEMAGICK_BINARY = "unset"
-else:
- if not os.path.exists(IMAGEMAGICK_BINARY):
- raise IOError(f"ImageMagick binary cannot be found at {IMAGEMAGICK_BINARY}")
-
- if not os.path.isfile(IMAGEMAGICK_BINARY):
- raise IOError(f"ImageMagick binary found at {IMAGEMAGICK_BINARY} is not a file")
- success, err = try_cmd([IMAGEMAGICK_BINARY])
- if not success:
- raise IOError(
- f"{err} - The path specified for the ImageMagick binary might "
- f"be wrong: {IMAGEMAGICK_BINARY}"
- )
-
-
def check():
- """Check if moviepy has found the binaries of FFmpeg and ImageMagick."""
+ """Check if moviepy has found the binaries for FFmpeg."""
if try_cmd([FFMPEG_BINARY])[0]:
print(f"MoviePy: ffmpeg successfully found in '{FFMPEG_BINARY}'.")
else: # pragma: no cover
print(f"MoviePy: can't find or access ffmpeg in '{FFMPEG_BINARY}'.")
- if try_cmd([IMAGEMAGICK_BINARY])[0]:
- print(f"MoviePy: ImageMagick successfully found in '{IMAGEMAGICK_BINARY}'.")
- else: # pragma: no cover
- print(f"MoviePy: can't find or access ImageMagick in '{IMAGEMAGICK_BINARY}'.")
-
if DOTENV:
print(f"\n.env file content at {DOTENV}:\n")
print(Path(DOTENV).read_text())
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index c45d2284..a88a723b 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -13,10 +13,11 @@ from numbers import Real
import numpy as np
import proglog
from imageio import imread, imsave
-from PIL import Image
+from PIL import Image, ImageDraw, ImageFont
+
+from typing import List, Dict
from moviepy.Clip import Clip
-from moviepy.config import IMAGEMAGICK_BINARY
from moviepy.decorators import (
add_mask_if_none,
apply_to_mask,
@@ -36,9 +37,7 @@ from moviepy.tools import (
)
from moviepy.video.io.ffmpeg_writer import ffmpeg_write_video
from moviepy.video.io.gif_writers import (
- write_gif,
- write_gif_with_image_io,
- write_gif_with_tempfiles,
+ write_gif_with_imageio,
)
from moviepy.video.tools.drawing import blit
@@ -461,20 +460,14 @@ class VideoClip(Clip):
self,
filename,
fps=None,
- program="imageio",
opt="nq",
- fuzz=1,
loop=0,
- dispose=False,
colors=None,
- tempfiles=False,
logger="bar",
- pixel_format=None,
):
"""Write the VideoClip to a GIF file.
- Converts a VideoClip into an animated GIF using ImageMagick
- or ffmpeg.
+ Converts a VideoClip into an animated GIF using imageio
Parameters
----------
@@ -487,34 +480,19 @@ class VideoClip(Clip):
isn't provided, then the function will look for the clip's
``fps`` attribute (VideoFileClip, for instance, have one).
- program
- Software to use for the conversion, either 'imageio' (this will use
- the library FreeImage through ImageIO), or 'ImageMagick', or 'ffmpeg'.
-
opt
Optimalization to apply. If program='imageio', opt must be either 'wu'
- (Wu) or 'nq' (Neuquant). If program='ImageMagick',
- either 'optimizeplus' or 'OptimizeTransparency'.
+ (Wu) or 'nq' (Neuquant).
- fuzz
- (ImageMagick only) Compresses the GIF by considering that
- the colors that are less than fuzz% different are in fact
- the same.
+ loop : int, optional
+ Repeat the clip using ``loop`` iterations in the resulting GIF.
- tempfiles
- Writes every frame to a file instead of passing them in the RAM.
- Useful on computers with little RAM. Can only be used with
- ImageMagick' or 'ffmpeg'.
+ colors : int, optional
+ Defines the maximum number of colors that the output image will have.
progress_bar
If True, displays a progress bar
- pixel_format
- Pixel format for the output gif file. If is not specified
- 'rgb24' will be used as the default format unless ``clip.mask``
- exist, then 'rgba' will be used. This option is only going to
- be accepted if ``program=ffmpeg`` or when ``tempfiles=True``
-
Notes
-----
@@ -530,50 +508,15 @@ class VideoClip(Clip):
# A little sketchy at the moment, maybe move all that in write_gif,
# refactor a little... we will see.
- if program == "imageio":
- write_gif_with_image_io(
- self,
- filename,
- fps=fps,
- opt=opt,
- loop=loop,
- colors=colors,
- logger=logger,
- )
- elif tempfiles:
- # convert imageio opt variable to something that can be used with
- # ImageMagick
- opt = "optimizeplus" if opt == "nq" else "OptimizeTransparency"
- write_gif_with_tempfiles(
- self,
- filename,
- fps=fps,
- program=program,
- opt=opt,
- fuzz=fuzz,
- loop=loop,
- dispose=dispose,
- colors=colors,
- logger=logger,
- pixel_format=pixel_format,
- )
- else:
- # convert imageio opt variable to something that can be used with
- # ImageMagick
- opt = "optimizeplus" if opt == "nq" else "OptimizeTransparency"
- write_gif(
- self,
- filename,
- fps=fps,
- program=program,
- opt=opt,
- fuzz=fuzz,
- loop=loop,
- dispose=dispose,
- colors=colors,
- logger=logger,
- pixel_format=pixel_format,
- )
+ write_gif_with_imageio(
+ self,
+ filename,
+ fps=fps,
+ opt=opt,
+ loop=loop,
+ colors=colors,
+ logger=logger,
+ )
# -----------------------------------------------------------------
# F I L T E R I N G
@@ -1202,212 +1145,271 @@ class ColorClip(ImageClip):
class TextClip(ImageClip):
- """Class for autogenerated text clips.
+ """Class for autogenerated text clips.
- Creates an ImageClip originating from a script-generated text image.
- Requires ImageMagick.
+ Creates an ImageClip originating from a script-generated text image.
- Parameters
- ----------
+ Parameters
+ ----------
- text
- A string of the text to write. Can be replaced by argument
- ``filename``.
+ text
+ A string of the text to write. Can be replaced by argument
+ ``filename``.
- filename
- The name of a file in which there is the text to write,
- as a string or a path-like object.
- Can be provided instead of argument ``txt``
+ filename
+ The name of a file in which there is the text to write,
+ as a string or a path-like object.
+ Can be provided instead of argument ``text``
- size
- Size of the picture in pixels. Can be auto-set if
- method='label', but mandatory if method='caption'.
- the height can be None, it will then be auto-determined.
+ font_size
+ Font size in point. Can be auto-set if method='caption',
+ or if method='label' and size is set.
- bg_color
- Color of the background. See ``TextClip.list('color')``
- for a list of acceptable names.
+ font
+ Path to the font to use. Must be an OpenType font.
+ See ``TextClip.list('font')`` for the list of fonts you can use on
+ your computer.
- color
- Color of the text. See ``TextClip.list('color')`` for a
- list of acceptable names.
+ size
+ Size of the picture in pixels. Can be auto-set if
+ method='label' and font_size is set, but mandatory if method='caption'.
+ the height can be None for caption if font_size is defined,
+ it will then be auto-determined.
- font
- Name of the font to use. See ``TextClip.list('font')`` for
- the list of fonts you can use on your computer.
+ bg_color
+ Color of the background. Default to None for no background. Can be
+ a RGB (or RGBA if transparent = ``True``) ``tuple``, a color name, or an
+ hexadecimal notation.
- stroke_color
- Color of the stroke (=contour line) of the text. If ``None``,
- there will be no stroke.
+ color
+ Color of the text. See ``TextClip.list('color')`` for a
+ list of acceptable names.
- stroke_width
- Width of the stroke, in pixels. Can be a float, like 1.5.
+
+ stroke_color
+ Color of the stroke (=contour line) of the text. If ``None``,
+ there will be no stroke.
- method
- Either 'label' (default, the picture will be autosized so as to fit
- exactly the size) or 'caption' (the text will be drawn in a picture
- with fixed size provided with the ``size`` argument). If `caption`,
- the text will be wrapped automagically (sometimes it is buggy, not
- my fault, complain to the ImageMagick crew) and can be aligned or
- centered (see parameter ``align``).
+ stroke_width
+ Width of the stroke, in pixels. Can be a float, like 1.5.
- kerning
- Changes the default spacing between letters. For
- instance ``kerning=-1`` will make the letters 1 pixel nearer from
- ach other compared to the default spacing.
+ method
+ Either 'label' (default, the picture will be autosized so as to fit
+ exactly the size) or 'caption' (the text will be drawn in a picture
+ with fixed size provided with the ``size`` argument). If `caption`,
+ the text will be wrapped automagically.
- align
- center | East | West | South | North . Will only work if ``method``
- is set to ``caption``
+ text_align
+ center | left | right. Text align similar to css. Default to ``center``.
- transparent
- ``True`` (default) if you want to take into account the
- transparency in the image.
- """
+ horizontal_align
+ center | left | right. Define horizontal align of text bloc in image.
+ Default to ``center``.
- @convert_path_to_string("filename")
- def __init__(
- self,
- text=None,
- filename=None,
- size=None,
- color="black",
- bg_color="transparent",
- font_size=None,
- font="Courier",
- stroke_color=None,
- stroke_width=1,
- method="label",
- kerning=None,
- align="center",
- interline=None,
- tempfilename=None,
- temptxt=None,
- transparent=True,
- remove_temp=True,
- print_cmd=False,
- ):
- if text is not None:
- if temptxt is None:
- temptxt_fd, temptxt = tempfile.mkstemp(suffix=".txt")
- try: # only in Python3 will this work
- os.write(temptxt_fd, bytes(text, "UTF8"))
- except TypeError: # oops, fall back to Python2
- os.write(temptxt_fd, text)
- os.close(temptxt_fd)
- text = "@" + temptxt
- elif filename is not None:
- # use a file instead of a text.
- text = "@" + filename
- else:
- raise ValueError(
- "You must provide either 'text' or 'filename' arguments to TextClip"
- )
+ vertical_align
+ center | top | bottom. Define vertical align of text bloc in image.
+ Default to ``center``.
- if size is not None:
- size = (
- "" if size[0] is None else str(size[0]),
- "" if size[1] is None else str(size[1]),
- )
+ interline
+ Interline spacing. Default to ``4``.
- cmd = [
- IMAGEMAGICK_BINARY,
- "-background",
- bg_color,
- "-fill",
- color,
- "-font",
- font,
- ]
-
- if font_size is not None:
- cmd += ["-pointsize", "%d" % font_size]
- if kerning is not None:
- cmd += ["-kerning", "%0.1f" % kerning]
- if stroke_color is not None:
- cmd += ["-stroke", stroke_color, "-strokewidth", "%.01f" % stroke_width]
- if size is not None:
- cmd += ["-size", "%sx%s" % (size[0], size[1])]
- if align is not None:
- cmd += ["-gravity", align]
- if interline is not None:
- cmd += ["-interline-spacing", "%d" % interline]
-
- if tempfilename is None:
- tempfile_fd, tempfilename = tempfile.mkstemp(suffix=".png")
- os.close(tempfile_fd)
-
- cmd += [
- "%s:%s" % (method, text),
- "-type",
- "truecolormatte",
- "PNG32:%s" % tempfilename,
- ]
-
- if print_cmd:
- print(" ".join(cmd))
-
- try:
- subprocess_call(cmd, logger=None)
- except (IOError, OSError) as err:
- error = (
- f"MoviePy Error: creation of {filename} failed because of the "
- f"following error:\n\n{err}.\n\n."
- "This error can be due to the fact that ImageMagick "
- "is not installed on your computer, or (for Windows "
- "users) that you didn't specify the path to the "
- "ImageMagick binary. Check the documentation."
- )
- raise IOError(error)
-
- ImageClip.__init__(self, tempfilename, transparent=transparent)
- self.text = text
- self.color = color
- self.stroke_color = stroke_color
-
- if remove_temp:
- if tempfilename is not None and os.path.exists(tempfilename):
- os.remove(tempfilename)
- if temptxt is not None and os.path.exists(temptxt):
- os.remove(temptxt)
-
- @staticmethod
- def list(arg):
- """Returns a list of all valid entries for the ``font`` or ``color`` argument of
- ``TextClip``.
+ transparent
+ ``True`` (default) if you want to take into account the
+ transparency in the image.
"""
- popen_params = cross_platform_popen_params(
- {"stdout": sp.PIPE, "stderr": sp.DEVNULL, "stdin": sp.DEVNULL}
- )
-
- process = sp.Popen(
- [IMAGEMAGICK_BINARY, "-list", arg], encoding="utf-8", **popen_params
- )
- result = process.communicate()[0]
- lines = result.splitlines()
-
- if arg == "font":
- # Slice removes first 8 characters: " Font: "
- return [line[8:] for line in lines if line.startswith(" Font:")]
- elif arg == "color":
- # Each line is of the format "aqua srgb(0,255,255) SVG" so split
- # on space and take the first item to get the color name.
- # The first 5 lines are header information, not colors, so ignore
- return [line.split(" ")[0] for line in lines[5:]]
- else:
- raise Exception("MoviePy Error: Argument must equal 'font' or 'color'")
- @staticmethod
- def search(string, arg):
- """Returns the of all valid entries which contain ``string`` for the
- argument ``arg`` of ``TextClip``, for instance
-
- >>> # Find all the available fonts which contain "Courier"
- >>> print(TextClip.search('Courier', 'font'))
- """
- string = string.lower()
- names_list = TextClip.list(arg)
- return [name for name in names_list if string in name.lower()]
+ @convert_path_to_string("filename")
+ def __init__(
+ self,
+ font,
+ text=None,
+ filename=None,
+ font_size=None,
+ size=(None, None),
+ color="black",
+ bg_color=None,
+ stroke_color=None,
+ stroke_width=0,
+ method="label",
+ text_align="left",
+ horizontal_align="center",
+ vertical_align="center",
+ interline=4,
+ transparent=True,
+ duration=None
+ ):
+
+ def break_text (width, text, font, font_size, stroke_width, align, spacing) -> List[str] :
+ """
+ Break text to never overflow a width
+ """
+ img = Image.new("RGB", (1, 1))
+ font_pil = ImageFont.truetype(font, font_size)
+ draw = ImageDraw.Draw(img)
+
+ lines = []
+ current_line = ''
+ words = text.split(' ')
+ for word in words:
+ temp_line = (current_line + ' ' + word if current_line else word)
+ temp_left, temp_top, temp_right, temp_bottom = draw.multiline_textbbox((0,0), temp_line, font=font_pil, spacing=spacing,
+ align=align, stroke_width=stroke_width)
+ temp_width = temp_right - temp_left
+
+ if temp_width <= width:
+ current_line = temp_line
+ else:
+ lines.append(current_line)
+ current_line = word
+
+ if current_line :
+ lines.append(current_line)
+
+ return lines
+
+ def find_text_size (text, font, font_size, stroke_width, align, spacing, max_width=None, allow_break=False) -> tuple[int, int] :
+ """
+ Find dimensions a text will occupy
+ return a tuple (width, height)
+ """
+ img = Image.new("RGB", (1, 1))
+ font_pil = ImageFont.truetype(font, font_size)
+ draw = ImageDraw.Draw(img)
+
+ if max_width is None or not allow_break:
+ left, top, right, bottom = draw.multiline_textbbox((0,0), text, font=font_pil, spacing=spacing,
+ align=align, stroke_width=stroke_width, anchor="lm")
+
+ return (int(right - left), int(bottom - top))
+
+ lines = break_text(width=max_width, text=text, font=font, font_size=font_size, stroke_width=stroke_width,
+ align=align, spacing=spacing)
+
+ left, top, right, bottom = draw.multiline_textbbox((0,0), "\n".join(lines), font=font_pil, spacing=spacing,
+ align=align, stroke_width=stroke_width, anchor="lm")
+
+ return (int(right - left), int(bottom - top))
+
+ def find_optimum_font_size (text, font, stroke_width, align, spacing, width, height=None, allow_break=False) :
+ """
+ Find the best font size to fit as optimally as possible
+ """
+ max_font_size = width
+ min_font_size = 1
+
+ # Try find best size using bisection
+ while min_font_size < max_font_size:
+ avg_font_size = int((max_font_size + min_font_size) // 2)
+ text_width, text_height = find_text_size(text, font, avg_font_size, stroke_width, align, spacing,
+ max_width=width, allow_break=allow_break)
+
+ if text_width <= width and (height is None or text_height <= height):
+ min_font_size = avg_font_size + 1
+ else:
+ max_font_size = avg_font_size - 1
+
+ # Check if the last font size tested fits within the given width and height
+ text_width, text_height = find_text_size(text, font, min_font_size, stroke_width, align, spacing,
+ max_width=width, allow_break=allow_break)
+ if text_width <= width and (height is None or text_height <= height):
+ return min_font_size
+ else:
+ return min_font_size - 1
+
+ try :
+ _ = ImageFont.truetype(font)
+ except Exception as e :
+ raise ValueError("Invalid font {}, pillow failed to use it with error {}".format(font, e))
+
+ if filename:
+ with open(filename, 'r') as file:
+ text = file.read()
+
+ if text is None :
+ raise ValueError("No text nor filename provided")
+
+ # Compute all img and text sizes if some are missing
+ img_width, img_height = size
+
+ if method == "caption" :
+ if img_width is None :
+ raise ValueError("Size is mandatory when method is caption")
+
+ if img_height is None and font_size is None :
+ raise ValueError("Height is mandatory when method is caption and font size is None")
+
+ if font_size is None :
+ font_size = find_optimum_font_size(text=text, font=font, stroke_width=stroke_width, align=text_align,
+ spacing=interline, width=img_width, height=img_height, allow_break=True)
+
+ if img_height is None :
+ img_height = find_text_size(text=text, font=font, font_size=font_size, stroke_width=stroke_width,
+ align=text_align, spacing=interline, max_width=img_width, allow_break=True)[1]
+
+ # Add line breaks whenever needed
+ text = "\n".join(break_text(width=img_width, text=text, font=font, font_size=font_size, stroke_width=stroke_width,
+ align=text_align, spacing=interline))
+
+ elif method == "label" :
+ if font_size is None and img_width is None :
+ raise ValueError("Font size is mandatory when method is label and size is None")
+
+ if font_size is None :
+ font_size = find_optimum_font_size(text=text, font=font, stroke_width=stroke_width, align=text_align,
+ spacing=interline, width=img_width, height=img_height)
+
+ if img_width is None :
+ img_width = find_text_size(text=text, font=font, font_size=font_size, stroke_width=stroke_width,
+ align=text_align, spacing=interline)[0]
+
+ if img_height is None :
+ img_height = find_text_size(text=text, font=font, font_size=font_size, stroke_width=stroke_width,
+ align=text_align, spacing=interline, max_width=img_width)[1]
+
+ else :
+ raise ValueError("Method must be either `caption` or `label`.")
+
+ # Trace the image
+ img_mode = "RGBA" if transparent else "RGB"
+ img = Image.new(img_mode, (img_width, img_height), color=bg_color)
+ pil_font = ImageFont.truetype(font, font_size)
+ draw = ImageDraw.Draw(img)
+
+ # Dont need allow break here, because we already breaked in caption
+ text_width, text_height = find_text_size(text=text, font=font, font_size=font_size, stroke_width=stroke_width,
+ align=text_align, spacing=interline, max_width=img_width)
+
+ x = 0
+ if horizontal_align == "right" :
+ x = img_width - text_width
+ elif horizontal_align == "center" :
+ x = (img_width - text_width) / 2
+
+ y = 0
+ if vertical_align == "bottom" :
+ y = img_height - text_height
+ elif vertical_align == "center" :
+ y = (img_height - text_height) / 2
+
+
+ # So, pillow multiline support is horrible, in particular multiline_text and multiline_textbbox
+ # are not intuitive at all. They cannot use left top (see https://pillow.readthedocs.io/en/stable/handbook/text-anchors.html)
+ # as anchor, so we always have to use left middle instead. Else we would always have a useless
+ # margin (the diff between ascender and top) on any text.
+ # That mean our Y is actually not from 0 for top, but need to be increment by half our text height,
+ # since we have to reference from middle line.
+ y += text_height/2
+
+ draw.multiline_text(xy=(x, y), text=text, fill=color, font=pil_font, spacing=interline, align=text_align stroke_width=stroke_width,
+ stroke_fill=stroke_color, anchor="lm")
+
+ # We just need the image as a numpy array
+ img_numpy = np.array(img)
+
+ ImageClip.__init__(self, img=img_numpy, transparent=transparent, duration=duration)
+ self.text = text
+ self.color = color
+ self.stroke_color = stroke_color
class BitmapClip(VideoClip):
diff --git a/moviepy/video/io/ImageSequenceClip.py b/moviepy/video/io/ImageSequenceClip.py
index 5d5864a1..d4d012c9 100644
--- a/moviepy/video/io/ImageSequenceClip.py
+++ b/moviepy/video/io/ImageSequenceClip.py
@@ -38,6 +38,11 @@ class ImageSequenceClip(VideoClip):
is_mask
Will this sequence of pictures be used as an animated mask.
+
+ load_images
+ Specify that all images should be loaded into the RAM. This is only
+ interesting if you have a small number of images that will be used
+ more than once.
"""
def __init__(
diff --git a/moviepy/video/io/gif_writers.py b/moviepy/video/io/gif_writers.py
index f4240139..ba8992c1 100644
--- a/moviepy/video/io/gif_writers.py
+++ b/moviepy/video/io/gif_writers.py
@@ -1,441 +1,21 @@
"""MoviePy video GIFs writing."""
-import os
-import subprocess as sp
-
-import numpy as np
import proglog
-
-from moviepy.config import FFMPEG_BINARY, IMAGEMAGICK_BINARY
from moviepy.decorators import requires_duration, use_clip_fps_by_default
-from moviepy.tools import cross_platform_popen_params, subprocess_call
-from moviepy.video.fx.loop import loop as loop_fx
-
-
-try:
- import imageio
-
- IMAGEIO_FOUND = True
-except ImportError:
- IMAGEIO_FOUND = False
-
+import imageio
@requires_duration
@use_clip_fps_by_default
-def write_gif_with_tempfiles(
- clip,
- filename,
- fps=None,
- program="ImageMagick",
- opt="OptimizeTransparency",
- fuzz=1,
- loop=0,
- dispose=True,
- colors=None,
- pixel_format=None,
- logger="bar",
+def write_gif_with_imageio(
+ clip, filename, fps=None, opt=0, loop=0, colors=None, logger="bar"
):
- """Write the VideoClip to a GIF file.
-
-
- Converts a VideoClip into an animated GIF using ImageMagick
- or ffmpeg. Does the same as write_gif (see this one for more
- docstring), but writes every frame to a file instead of passing
- them in the RAM. Useful on computers with little RAM.
-
- Parameters
- ----------
-
- clip : moviepy.video.VideoClip.VideoClip
- The clip from which the frames will be extracted to create the GIF image.
-
- filename : str
- Name of the resulting gif file.
-
- fps : int, optional
- Number of frames per second. If it isn't provided, then the function will
- look for the clip's ``fps`` attribute.
-
- program : str, optional
- Software to use for the conversion, either ``"ImageMagick"`` or
- ``"ffmpeg"``.
-
- opt : str, optional
- ImageMagick only optimalization to apply, either ``"optimizeplus"`` or
- ``"OptimizeTransparency"``. Doesn't takes effect if ``program="ffmpeg"``.
-
- fuzz : float, optional
- ImageMagick only compression option which compresses the GIF by
- considering that the colors that are less than ``fuzz`` different are in
- fact the same.
-
- loop : int, optional
- Repeat the clip using ``loop`` iterations in the resulting GIF.
-
- dispose : bool, optional
- ImageMagick only option which, when enabled, the ImageMagick binary will
- take the argument `-dispose 2`, clearing the frame area with the
- background color, otherwise it will be defined as ``-dispose 1`` which
- will not dispose, just overlays next frame image.
-
- colors : int, optional
- ImageMagick only option for color reduction. Defines the maximum number
- of colors that the output image will have.
-
- pixel_format : str, optional
- FFmpeg pixel format for the output gif file. If is not specified
- ``"rgb24"`` will be used as the default format unless ``clip.mask``
- exist, then ``"rgba"`` will be used. Doesn't takes effect if
- ``program="ImageMagick"``.
-
- logger : str, optional
- Either ``"bar"`` for progress bar or ``None`` or any Proglog logger.
"""
- logger = proglog.default_bar_logger(logger)
- file_root, ext = os.path.splitext(filename)
- tt = np.arange(0, clip.duration, 1.0 / fps)
-
- tempfiles = []
-
- logger(message="MoviePy - Building file %s\n" % filename)
- logger(message="MoviePy - - Generating GIF frames")
-
- for i, t in logger.iter_bar(t=list(enumerate(tt))):
- name = "%s_GIFTEMP%04d.png" % (file_root, i + 1)
- tempfiles.append(name)
- clip.save_frame(name, t, with_mask=True)
-
- delay = int(100.0 / fps)
-
- if clip.mask is None:
- with_mask = False
-
- if program == "ImageMagick":
- if not pixel_format:
- pixel_format = "RGBA" if with_mask else "RGB"
-
- logger(message="MoviePy - - Optimizing GIF with ImageMagick...")
- cmd = (
- [
- IMAGEMAGICK_BINARY,
- "-delay",
- "%d" % delay,
- "-dispose",
- "%d" % (2 if dispose else 1),
- "-loop",
- "%d" % loop,
- "%s_GIFTEMP*.png" % file_root,
- "-coalesce",
- "-fuzz",
- "%02d" % fuzz + "%",
- "-layers",
- "%s" % opt,
- "-set",
- "colorspace",
- pixel_format,
- ]
- + (["-colors", "%d" % colors] if colors is not None else [])
- + [filename]
- )
-
- elif program == "ffmpeg":
- if loop:
- clip = loop_fx(clip, n=loop)
-
- if not pixel_format:
- pixel_format = "rgba" if with_mask else "rgb24"
-
- cmd = [
- FFMPEG_BINARY,
- "-y",
- "-f",
- "image2",
- "-r",
- str(fps),
- "-i",
- file_root + "_GIFTEMP%04d.png",
- "-r",
- str(fps),
- filename,
- "-pix_fmt",
- (pixel_format),
- ]
-
- try:
- subprocess_call(cmd, logger=logger)
- logger(message="MoviePy - GIF ready: %s." % filename)
-
- except (IOError, OSError) as err:
- error = (
- "MoviePy Error: creation of %s failed because "
- "of the following error:\n\n%s.\n\n." % (filename, str(err))
- )
-
- if program == "ImageMagick":
- error += (
- "This error can be due to the fact that "
- "ImageMagick is not installed on your computer, or "
- "(for Windows users) that you didn't specify the "
- "path to the ImageMagick binary. Check the documentation."
- )
-
- raise IOError(error)
-
- for file in tempfiles:
- os.remove(file)
-
-
-@requires_duration
-@use_clip_fps_by_default
-def write_gif(
- clip,
- filename,
- fps=None,
- with_mask=True,
- program="ImageMagick",
- opt="OptimizeTransparency",
- fuzz=1,
- loop=0,
- dispose=True,
- colors=None,
- pixel_format=None,
- logger="bar",
-):
- """Write the VideoClip to a GIF file, without temporary files.
-
- Converts a VideoClip into an animated GIF using ImageMagick
- or ffmpeg.
-
-
- Parameters
- ----------
-
- clip : moviepy.video.VideoClip.VideoClip
- The clip from which the frames will be extracted to create the GIF image.
-
- filename : str
- Name of the resulting gif file.
-
- fps : int, optional
- Number of frames per second. If it isn't provided, then the function will
- look for the clip's ``fps`` attribute.
-
- with_mask : bool, optional
- Includes the mask of the clip in the output (the clip must have a mask
- if this argument is ``True``).
-
- program : str, optional
- Software to use for the conversion, either ``"ImageMagick"`` or
- ``"ffmpeg"``.
-
- opt : str, optional
- ImageMagick only optimalization to apply, either ``"optimizeplus"`` or
- ``"OptimizeTransparency"``. Doesn't takes effect if ``program="ffmpeg"``.
-
- fuzz : float, optional
- ImageMagick only compression option which compresses the GIF by
- considering that the colors that are less than ``fuzz`` different are in
- fact the same.
-
- loop : int, optional
- Repeat the clip using ``loop`` iterations in the resulting GIF.
-
- dispose : bool, optional
- ImageMagick only option which, when enabled, the ImageMagick binary will
- take the argument `-dispose 2`, clearing the frame area with the
- background color, otherwise it will be defined as ``-dispose 1`` which
- will not dispose, just overlays next frame image.
-
- colors : int, optional
- ImageMagick only option for color reduction. Defines the maximum number
- of colors that the output image will have.
-
- pixel_format : str, optional
- FFmpeg pixel format for the output gif file. If is not specified
- ``"rgb24"`` will be used as the default format unless ``clip.mask``
- exist, then ``"rgba"`` will be used. Doesn't takes effect if
- ``program="ImageMagick"``.
-
- logger : str, optional
- Either ``"bar"`` for progress bar or ``None`` or any Proglog logger.
-
-
- Examples
- --------
-
- The gif will be playing the clip in real time, you can only change the
- frame rate. If you want the gif to be played slower than the clip you will
- use:
-
- >>> # slow down clip 50% and make it a GIF
- >>> myClip.multiply_speed(0.5).write_gif('myClip.gif')
+ Writes the gif with the Python library ImageIO (calls FreeImage).
"""
- #
- # We use processes chained with pipes.
- #
- # if program == 'ffmpeg'
- # frames --ffmpeg--> gif
- #
- # if program == 'ImageMagick' and optimize == (None, False)
- # frames --ffmpeg--> bmp frames --ImageMagick--> gif
- #
- #
- # if program == 'ImageMagick' and optimize != (None, False)
- # frames -ffmpeg-> bmp frames -ImagMag-> gif -ImagMag-> better gif
- #
-
- delay = 100.0 / fps
- logger = proglog.default_bar_logger(logger)
- if clip.mask is None:
- with_mask = False
- if not pixel_format:
- pixel_format = "rgba" if with_mask else "rgb24"
-
- cmd1 = [
- FFMPEG_BINARY,
- "-y",
- "-loglevel",
- "error",
- "-f",
- "rawvideo",
- "-vcodec",
- "rawvideo",
- "-r",
- "%.02f" % fps,
- "-s",
- "%dx%d" % (clip.w, clip.h),
- "-pix_fmt",
- (pixel_format),
- "-i",
- "-",
- ]
-
- popen_params = cross_platform_popen_params(
- {"stdout": sp.DEVNULL, "stderr": sp.DEVNULL, "stdin": sp.DEVNULL}
- )
-
- if program == "ffmpeg":
- if loop:
- clip = loop_fx(clip, n=loop)
-
- popen_params["stdin"] = sp.PIPE
- popen_params["stdout"] = sp.DEVNULL
-
- proc1 = sp.Popen(
- cmd1
- + [
- "-pix_fmt",
- (pixel_format),
- "-r",
- "%.02f" % fps,
- filename,
- ],
- **popen_params,
- )
- else:
- popen_params["stdin"] = sp.PIPE
- popen_params["stdout"] = sp.PIPE
-
- proc1 = sp.Popen(
- cmd1 + ["-f", "image2pipe", "-vcodec", "bmp", "-"], **popen_params
- )
-
- if program == "ImageMagick":
- cmd2 = [
- IMAGEMAGICK_BINARY,
- "-delay",
- "%.02f" % (delay),
- "-dispose",
- "%d" % (2 if dispose else 1),
- "-loop",
- "%d" % loop,
- "-",
- "-coalesce",
- ]
-
- if opt in [False, None]:
- popen_params["stdin"] = proc1.stdout
- popen_params["stdout"] = sp.DEVNULL
- proc2 = sp.Popen(cmd2 + [filename], **popen_params)
-
- else:
- popen_params["stdin"] = proc1.stdout
- popen_params["stdout"] = sp.PIPE
- proc2 = sp.Popen(cmd2 + ["gif:-"], **popen_params)
-
- if opt:
- cmd3 = (
- [
- IMAGEMAGICK_BINARY,
- "-",
- "-fuzz",
- "%d" % fuzz + "%",
- "-layers",
- opt,
- ]
- + (["-colors", "%d" % colors] if colors is not None else [])
- + [filename]
- )
-
- popen_params["stdin"] = proc2.stdout
- popen_params["stdout"] = sp.DEVNULL
- proc3 = sp.Popen(cmd3, **popen_params)
-
- # We send all the frames to the first process
- logger(message="MoviePy - Building file %s" % filename)
- logger(message="MoviePy - - Generating GIF frames.")
- try:
- for t, frame in clip.iter_frames(
- fps=fps, logger=logger, with_times=True, dtype="uint8"
- ):
- if with_mask:
- mask = 255 * clip.mask.get_frame(t)
- frame = np.dstack([frame, mask]).astype("uint8")
- proc1.stdin.write(frame.tobytes())
-
- except IOError as err:
- error = (
- "[MoviePy] Error: creation of %s failed because "
- "of the following error:\n\n%s.\n\n." % (filename, str(err))
- )
-
- if program == "ImageMagick":
- error += (
- "This can be due to the fact that "
- "ImageMagick is not installed on your computer, or "
- "(for Windows users) that you didn't specify the "
- "path to the ImageMagick binary. Check the documentation."
- )
-
- raise IOError(error)
- if program == "ImageMagick":
- logger(message="MoviePy - - Optimizing GIF with ImageMagick.")
- proc1.stdin.close()
- proc1.wait()
- if program == "ImageMagick":
- proc2.wait()
- if opt:
- proc3.wait()
- logger(message="MoviePy - - File ready: %s." % filename)
-
-
-def write_gif_with_image_io(
- clip, filename, fps=None, opt=0, loop=0, colors=None, logger="bar"
-):
- """Writes the gif with the Python library ImageIO (calls FreeImage)."""
if colors is None:
colors = 256
logger = proglog.default_bar_logger(logger)
- if not IMAGEIO_FOUND:
- raise ImportError(
- "Writing a gif with imageio requires ImageIO installed,"
- " with e.g. 'pip install imageio'"
- )
-
- if fps is None:
- fps = clip.fps
-
quantizer = 0 if opt != 0 else "nq"
writer = imageio.save(
diff --git a/setup.py b/setup.py
index 751ee835..25c4aeea 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@
import sys
from pathlib import Path
-
+from moviepy.version import __version__
try:
from setuptools import find_packages, setup
@@ -65,8 +65,6 @@ if "build_docs" in sys.argv:
cmdclass["build_docs"] = BuildDoc
-__version__ = Path("moviepy/version.py").read_text().strip().split('"')[1][:-1]
-
# Define the requirements for specific execution needs.
requires = [
@@ -75,23 +73,19 @@ requires = [
"imageio_ffmpeg>=0.2.0",
"numpy>=1.17.3",
"proglog<=1.0.0",
-]
-
-optional_reqs = [
"pygame>=1.9.3",
"python-dotenv>=0.10",
"opencv-python",
"scikit-image",
"scikit-learn",
"scipy",
- "matplotlib",
- "youtube_dl",
+ "pillow>=9.2.0,<11.0", # We are good at least up to v11
]
doc_reqs = [
"numpydoc<2.0",
- "Sphinx==3.4.3",
- "sphinx-rtd-theme==0.5.1",
+ "Sphinx==6.*",
+ "sphinx-rtd-theme==1.2.2",
]
test_reqs = [
@@ -112,7 +106,6 @@ lint_reqs = [
]
extra_reqs = {
- "optional": optional_reqs,
"doc": doc_reqs,
"test": test_reqs,
"lint": lint_reqs,
diff --git a/tests/conftest.py b/tests/conftest.py
index e0626337..0ed93dd7 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -35,7 +35,7 @@ else:
@functools.lru_cache(maxsize=None)
def get_video(start_time=0, end_time=1):
- return VideoFileClip("media/big_buck_bunny_432_433.webm").subclip(
+ return VideoFileClip("media/big_buck_bunny_432_433.webm").with_subclip(
start_time, end_time
)
diff --git a/tests/test_AudioClips.py b/tests/test_AudioClips.py
index 67865d74..ca62c1b4 100644
--- a/tests/test_AudioClips.py
+++ b/tests/test_AudioClips.py
@@ -162,7 +162,7 @@ def test_concatenate_audioclip_with_audiofileclip(util, stereo_wave):
def test_concatenate_audiofileclips(util):
- clip1 = AudioFileClip("media/crunching.mp3").subclip(1, 4)
+ clip1 = AudioFileClip("media/crunching.mp3").with_subclip(1, 4)
# Checks it works with videos as well
clip2 = AudioFileClip("media/big_buck_bunny_432_433.webm")
diff --git a/tests/test_Clip.py b/tests/test_Clip.py
index 19d51b9c..979cabc9 100644
--- a/tests/test_Clip.py
+++ b/tests/test_Clip.py
@@ -194,9 +194,9 @@ def test_clip_subclip(duration, start_time, end_time, expected_duration):
if hasattr(expected_duration, "__traceback__"):
with pytest.raises(expected_duration):
- clip.subclip(start_time=start_time, end_time=end_time)
+ clip.with_subclip(start_time=start_time, end_time=end_time)
else:
- sub_clip = clip.subclip(start_time=start_time, end_time=end_time)
+ sub_clip = clip.with_subclip(start_time=start_time, end_time=end_time)
assert sub_clip.duration == expected_duration
@@ -232,7 +232,7 @@ def test_clip_subclip(duration, start_time, end_time, expected_duration):
)
def test_clip_cutout(start_time, end_time, expected_frames):
clip = BitmapClip([["RR", "RR"], ["GG", "GG"], ["BB", "BB"]], fps=1)
- new_clip = clip.cutout(start_time, end_time)
+ new_clip = clip.with_cutout(start_time, end_time)
assert new_clip == BitmapClip(expected_frames, fps=1)
diff --git a/tests/test_SubtitlesClip.py b/tests/test_SubtitlesClip.py
index 911708f7..55f42720 100644
--- a/tests/test_SubtitlesClip.py
+++ b/tests/test_SubtitlesClip.py
@@ -42,7 +42,7 @@ def test_subtitles(util):
subtitles = SubtitlesClip("media/subtitles.srt", generator)
final = CompositeVideoClip([myvideo, subtitles])
- final.subclip(0, 0.5).write_videofile(
+ final.with_subclip(0, 0.5).write_videofile(
os.path.join(util.TMP_DIR, "subtitles.mp4"),
fps=5,
logger=None,
diff --git a/tests/test_VideoClip.py b/tests/test_VideoClip.py
index 63563053..c6a50983 100644
--- a/tests/test_VideoClip.py
+++ b/tests/test_VideoClip.py
@@ -101,7 +101,7 @@ def test_write_frame_errors_with_redirected_logs(util, video):
def test_write_videofiles_with_temp_audiofile_path(util):
- clip = VideoFileClip("media/big_buck_bunny_432_433.webm").subclip(0.2, 0.5)
+ clip = VideoFileClip("media/big_buck_bunny_432_433.webm").with_subclip(0.2, 0.5)
location = os.path.join(util.TMP_DIR, "temp_audiofile_path.webm")
temp_location = os.path.join(util.TMP_DIR, "temp_audiofile")
if not os.path.exists(temp_location):
@@ -188,58 +188,8 @@ def test_write_gif_imageio(util, video):
assert os.path.isfile(location)
-def test_write_gif_ffmpeg(util, video):
- clip = video(start_time=0.2, end_time=0.28)
- location = os.path.join(util.TMP_DIR, "ffmpeg_gif.gif")
- clip.write_gif(location, program="ffmpeg")
- assert os.path.isfile(location)
-
-
-def test_write_gif_ffmpeg_pixel_format(util, video):
- clip = video(start_time=0.2, end_time=0.28)
- location = os.path.join(util.TMP_DIR, "ffmpeg_gif.gif")
- clip.write_gif(location, program="ffmpeg", pixel_format="bgr24")
- assert os.path.isfile(location)
-
-
-def test_write_gif_ffmpeg_tmpfiles(util, video):
- clip = video(start_time=0.2, end_time=0.24)
- location = os.path.join(util.TMP_DIR, "ffmpeg_tmpfiles_gif.gif")
- clip.write_gif(location, program="ffmpeg", tempfiles=True)
- assert os.path.isfile(location)
-
-
-def test_write_gif_ffmpeg_tmpfiles_pixel_format(util, video):
- clip = video(start_time=0.2, end_time=0.24)
- location = os.path.join(util.TMP_DIR, "ffmpeg_tmpfiles_gif.gif")
- clip.write_gif(location, program="ffmpeg", tempfiles=True, pixel_format="bgr24")
- assert os.path.isfile(location)
-
-
-def test_write_gif_ImageMagick(util, video):
- clip = video(start_time=0.2, end_time=0.5)
- location = os.path.join(util.TMP_DIR, "imagemagick_gif.gif")
- clip.write_gif(location, program="ImageMagick")
- # Fails for some reason
- # assert os.path.isfile(location)
-
-
-def test_write_gif_ImageMagick_tmpfiles(util, video):
- clip = video(start_time=0.2, end_time=0.24)
- location = os.path.join(util.TMP_DIR, "imagemagick_tmpfiles_gif.gif")
- clip.write_gif(location, program="ImageMagick", tempfiles=True)
- assert os.path.isfile(location)
-
-
-def test_write_gif_ImageMagick_tmpfiles_pixel_format(util, video):
- clip = video(start_time=0.2, end_time=0.24)
- location = os.path.join(util.TMP_DIR, "imagemagick_tmpfiles_gif.gif")
- clip.write_gif(location, program="ImageMagick", tempfiles=True, pixel_format="SGI")
- assert os.path.isfile(location)
-
-
def test_subfx(util):
- clip = VideoFileClip("media/big_buck_bunny_0_30.webm").subclip(0, 1)
+ clip = VideoFileClip("media/big_buck_bunny_0_30.webm").with_subclip(0, 1)
transform = lambda c: multiply_speed(c, 0.5)
new_clip = clip.subfx(transform, 0.5, 0.8)
location = os.path.join(util.TMP_DIR, "subfx.mp4")
@@ -250,7 +200,7 @@ def test_subfx(util):
def test_oncolor(util):
# It doesn't need to be a ColorClip
clip = ColorClip(size=(100, 60), color=(255, 0, 0), duration=0.5)
- on_color_clip = clip.on_color(size=(200, 160), color=(0, 0, 255))
+ on_color_clip = clip.with_on_color(size=(200, 160), color=(0, 0, 255))
location = os.path.join(util.TMP_DIR, "oncolor.mp4")
on_color_clip.write_videofile(location, fps=24)
assert os.path.isfile(location)
@@ -283,7 +233,7 @@ def test_setaudio(util):
def test_setaudio_with_audiofile(util):
clip = ColorClip(size=(100, 60), color=(255, 0, 0), duration=0.5)
- audio = AudioFileClip("media/crunching.mp3").subclip(0, 0.5)
+ audio = AudioFileClip("media/crunching.mp3").with_subclip(0, 0.5)
clip = clip.with_audio(audio)
location = os.path.join(util.TMP_DIR, "setaudiofile.mp4")
clip.write_videofile(location, fps=24)
@@ -307,10 +257,10 @@ def test_with_layer():
reversed_composite_clip = CompositeVideoClip([top_clip, bottom_clip])
# Make sure that the order of clips makes no difference to the composite clip
- assert composite_clip.subclip(0, 2) == reversed_composite_clip.subclip(0, 2)
+ assert composite_clip.with_subclip(0, 2) == reversed_composite_clip.with_subclip(0, 2)
# Make sure that only the 'top' clip is kept
- assert top_clip.subclip(0, 2) == composite_clip.subclip(0, 2)
+ assert top_clip.subclip(0, 2) == composite_clip.with_subclip(0, 2)
# Make sure that it works even when there is only one clip playing at that time
target_clip = BitmapClip([["DEF"], ["EFD"], ["CAB"]], fps=1)
diff --git a/tests/test_VideoFileClip.py b/tests/test_VideoFileClip.py
index e92f78e0..4450c984 100644
--- a/tests/test_VideoFileClip.py
+++ b/tests/test_VideoFileClip.py
@@ -51,7 +51,7 @@ def test_copied_videofileclip_write_videofile(util):
input_video_filepath = "media/big_buck_bunny_432_433.webm"
output_video_filepath = os.path.join(util.TMP_DIR, "copied_videofileclip.mp4")
- clip = VideoFileClip(input_video_filepath).subclip(0, 1)
+ clip = VideoFileClip(input_video_filepath).with_subclip(0, 1)
copied_clip = clip.copy()
copied_clip.write_videofile(output_video_filepath)
diff --git a/tests/test_ffmpeg_reader.py b/tests/test_ffmpeg_reader.py
index f01127b7..6e132049 100644
--- a/tests/test_ffmpeg_reader.py
+++ b/tests/test_ffmpeg_reader.py
@@ -292,7 +292,7 @@ def test_ffmpeg_parse_video_rotation():
def test_correct_video_rotation(util):
"""See https://github.com/Zulko/moviepy/pull/577"""
- clip = VideoFileClip("media/rotated-90-degrees.mp4").subclip(0.2, 0.4)
+ clip = VideoFileClip("media/rotated-90-degrees.mp4").with_subclip(0.2, 0.4)
corrected_rotation_filename = os.path.join(
util.TMP_DIR,
diff --git a/tests/test_fx.py b/tests/test_fx.py
index 0f499030..5452a448 100644
--- a/tests/test_fx.py
+++ b/tests/test_fx.py
@@ -1382,7 +1382,7 @@ def test_multiply_volume_videoclip():
start_time, end_time = (0.1, 0.2)
clip = multiply_volume(
- VideoFileClip("media/chaplin.mp4").subclip(0, 0.3),
+ VideoFileClip("media/chaplin.mp4").with_subclip(0, 0.3),
0,
start_time=start_time,
end_time=end_time,
diff --git a/tests/test_issues.py b/tests/test_issues.py
index 5a3dbaaf..cfe89e17 100644
--- a/tests/test_issues.py
+++ b/tests/test_issues.py
@@ -235,7 +235,7 @@ def test_issue_334(util):
avatar.with_mask(maskclip) # must set maskclip here..
concatenated = avatar * 3
- tt = VideoFileClip("media/big_buck_bunny_0_30.webm").subclip(0, 3)
+ tt = VideoFileClip("media/big_buck_bunny_0_30.webm").with_subclip(0, 3)
# TODO: Setting mask here does not work:
# .with_mask(maskclip).resize(size)])
final = CompositeVideoClip([tt, concatenated.with_position(posi).fx(resize, size)])
@@ -362,13 +362,13 @@ def test_issue_470(util):
audio_clip = AudioFileClip("media/crunching.mp3")
# end_time is out of bounds
- subclip = audio_clip.subclip(start_time=6, end_time=9)
+ subclip = audio_clip.with_subclip(start_time=6, end_time=9)
with pytest.raises(IOError):
subclip.write_audiofile(wav_filename, write_logfile=True)
# but this one should work..
- subclip = audio_clip.subclip(start_time=6, end_time=8)
+ subclip = audio_clip.with_subclip(start_time=6, end_time=8)
subclip.write_audiofile(wav_filename, write_logfile=True)
@@ -386,7 +386,7 @@ def test_issue_547():
def test_issue_636():
- with VideoFileClip("media/big_buck_bunny_0_30.webm").subclip(0, 11) as video:
+ with VideoFileClip("media/big_buck_bunny_0_30.webm").with_subclip(0, 11) as video:
with video.subclip(0, 1) as _:
pass
@@ -395,9 +395,9 @@ def test_issue_655():
video_file = "media/fire2.mp4"
for subclip in [(0, 2), (1, 2), (2, 3)]:
with VideoFileClip(video_file) as v:
- with v.subclip(1, 2) as _:
+ with v.with_subclip(1, 2) as _:
pass
- next(v.subclip(*subclip).iter_frames())
+ next(v.with_subclip(*subclip).iter_frames())
assert True
diff --git a/tests/test_tools.py b/tests/test_tools.py
index 552d29c4..ced4a7be 100644
--- a/tests/test_tools.py
+++ b/tests/test_tools.py
@@ -154,55 +154,11 @@ def test_download_webfile(static_files_server, util, url, expected_result):
),
),
)
- (
- "imagemagick_binary",
- "imagemagick_binary_error",
- "imagemagick_binary_isfile",
- "imagemagick_binary_isdir",
- ),
- (
- pytest.param(
- "auto-detect",
- None,
- False,
- False,
- id="IMAGEMAGICK_BINARY=auto-detect",
- ),
- pytest.param(
- "foobarbazimpossible",
- (IOError, "ImageMagick binary cannot be found"),
- False,
- False,
- id="IMAGEMAGICK_BINARY=foobarbazimpossiblefile",
- ),
- pytest.param(
- "foobarbazimpossiblefile",
- (
- IOError,
- "The path specified for the ImageMagick binary might be wrong",
- ),
- True,
- False,
- id="IMAGEMAGICK_BINARY=foobarbazimpossible(file)",
- ),
- pytest.param(
- "foobarbazimpossibledir",
- (IOError, "is not a file"),
- False,
- True,
- id="IMAGEMAGICK_BINARY=foobarbazimpossible(dir)",
- ),
- ),
-)
+
def test_config(
util,
ffmpeg_binary,
ffmpeg_binary_error,
- imagemagick_binary,
- imagemagick_binary_error,
- imagemagick_binary_isfile,
- imagemagick_binary_isdir,
):
if "moviepy.config" in sys.modules:
del sys.modules["moviepy.config"]
@@ -212,36 +168,15 @@ def test_config(
prev_ffmpeg_binary = os.environ.get("FFMPEG_BINARY")
os.environ["FFMPEG_BINARY"] = ffmpeg_binary
- prev_imagemagick_binary = os.environ.get("IMAGEMAGICK_BINARY")
- if imagemagick_binary_isfile:
- imagemagick_binary = os.path.join(util.TMP_DIR, imagemagick_binary)
- with open(imagemagick_binary, "w") as f:
- f.write("foo")
- elif imagemagick_binary_isdir:
- imagemagick_binary = os.path.join(util.TMP_DIR, imagemagick_binary)
- if os.path.isdir(imagemagick_binary):
- shutil.rmtree(imagemagick_binary)
- os.mkdir(imagemagick_binary)
- os.environ["IMAGEMAGICK_BINARY"] = imagemagick_binary
if ffmpeg_binary_error is not None:
with pytest.raises(ffmpeg_binary_error[0]) as exc:
importlib.import_module("moviepy.config")
assert ffmpeg_binary_error[1] in str(exc.value)
- else:
- if imagemagick_binary_error is not None:
- with pytest.raises(imagemagick_binary_error[0]) as exc:
- importlib.import_module("moviepy.config")
- assert imagemagick_binary_error[1] in str(exc.value)
- else:
- importlib.import_module("moviepy.config")
if prev_ffmpeg_binary is not None:
os.environ["FFMPEG_BINARY"] = prev_ffmpeg_binary
- if prev_imagemagick_binary is not None:
- os.environ["IMAGEMAGICK_BINARY"] = prev_imagemagick_binary
-
if "moviepy.config" in sys.modules:
del sys.modules["moviepy.config"]
@@ -267,7 +202,6 @@ def test_config_check():
output = stdout.getvalue()
assert "MoviePy: ffmpeg successfully found in" in output
- assert "MoviePy: ImageMagick successfully found in" in output
if dotenv_module:
assert os.path.isfile(".env")
diff --git a/tests/test_videotools.py b/tests/test_videotools.py
index 94ba0a7f..8fd71bb4 100644
--- a/tests/test_videotools.py
+++ b/tests/test_videotools.py
@@ -92,7 +92,7 @@ def test_detect_scenes():
def test_find_video_period():
- clip = VideoFileClip("media/chaplin.mp4").subclip(0, 0.5).loop(2) # fps=25
+ clip = VideoFileClip("media/chaplin.mp4").with_subclip(0, 0.5).loop(2) # fps=25
# you need to increase the fps to get correct results
assert round(find_video_period(clip, fps=70), 6) == 0.5
@@ -314,7 +314,7 @@ def test_FramesMatches_select_scenes(
):
video_clip = VideoFileClip(filename)
if subclip is not None:
- video_clip = video_clip.subclip(subclip[0], subclip[1])
+ video_clip = video_clip.with_subclip(subclip[0], subclip[1])
clip = concatenate_videoclips([video_clip.fx(time_mirror), video_clip])
result = FramesMatches.from_clip(clip, 10, 3, logger=None).select_scenes(
match_threshold,
@@ -327,7 +327,7 @@ def test_FramesMatches_select_scenes(
def test_FramesMatches_write_gifs(util):
- video_clip = VideoFileClip("media/chaplin.mp4").subclip(0, 0.2)
+ video_clip = VideoFileClip("media/chaplin.mp4").with_subclip(0, 0.2)
clip = concatenate_videoclips([video_clip.fx(time_mirror), video_clip])
# add matching frame starting at start < clip.start which should be ignored
@@ -1094,7 +1094,7 @@ def test_find_objects(filename, expected_screenpos):
id="FakeClip",
),
pytest.param(
- VideoFileClip("media/chaplin.mp4").subclip(0, 1),
+ VideoFileClip("media/chaplin.mp4").with_subclip(0, 1),
None,
None,
None,