Skip to content

Video editing with Python

Improve VideoClip testing by inspecting numpy frame arrays (#1124)

Tom Burrows90e42c108dcb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b272ce29..da54ae50 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- If you were previously setting custom locations for FFmpeg or ImageMagick in ``config_defaults.py`` and MoviePy still cannot autodetect the binaries, you will need to switch to the new method using enviroment variables. [#1109]
### Added <!-- for new features -->
+- BitmapClip allows creating of custom frames using strings of letters
+- Clips can now be tested for equality with other clips using `==`. This checks whether every frame of the two clips are identical
- Support for path-like objects as an option wherever filenames are passed in as arguments [#1137]
- Autodetect ImageMagick executable on Windows [#1109]
- Optionally configure paths to FFmpeg and ImageMagick binaries with environment variables or a ``.env`` file [#1109]
@@ -22,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Optional `temp_audiofile_path` parameter in `VideoClip.write_videofile()` to specify where the temporary audiofile should be created [#1144]
### Changed <!-- for changes in existing functionality -->
+- `vfx.scroll` arguments `w` and `h` have had their order swapped. The correct order is now `w, h` but it is preferable to explicitly use keyword arguments
### Deprecated <!-- for soon-to-be removed features -->
@@ -42,6 +45,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- When using `VideoClip.write_videofile()` with `write_logfile=True`, errors would not be properly reported [#890]
- `TextClip.list("color")` now returns a list of bytes, not strings [#1119]
- `TextClip.search("colorname", "color")` does not crash with a TypeError [#1119]
+- `vfx.even_size` previously created clips with odd sizes [#1124]
+- `IndexError` in `vfx.freeze`, `vfx.time_mirror` and `vfx.time_symmetrize` [#1124]
- Using `rotate()` with a `ColorClip` no longer crashes [#1139]
diff --git a/moviepy/Clip.py b/moviepy/Clip.py
index 7e7483a0..e7427281 100644
--- a/moviepy/Clip.py
+++ b/moviepy/Clip.py
@@ -94,6 +94,7 @@ class Clip:
self.memoized_frame = frame
return frame
else:
+ # print(t)
return self.make_frame(t)
def fl(self, fun, apply_to=None, keep_duration=True):
@@ -270,7 +271,7 @@ class Clip:
@apply_to_audio
@convert_to_seconds(["t"])
@outplace
- def set_duration(self, t, change_end=True):
+ def set_duration(self, duration, change_end=True):
"""
Returns a copy of the clip, with the ``duration`` attribute
set to ``t``, which can be expressed in seconds (15.35), in (min, sec),
@@ -281,14 +282,14 @@ class Clip:
be modified in function of the duration and the preset end
of the clip.
"""
- self.duration = t
+ self.duration = duration
if change_end:
- self.end = None if (t is None) else (self.start + t)
+ self.end = None if (duration is None) else (self.start + duration)
else:
if self.duration is None:
raise Exception("Cannot change clip start when new" "duration is None")
- self.start = self.end - t
+ self.start = self.end - duration
@outplace
def set_make_frame(self, make_frame):
@@ -489,6 +490,23 @@ class Clip:
# * Therefore, should NOT be called by __del__().
pass
+ def __eq__(self, other):
+ if not isinstance(other, Clip):
+ return NotImplemented
+
+ # Make sure that the total number of frames is the same
+ self_length = self.duration * self.fps
+ other_length = other.duration * other.fps
+ if self_length != other_length:
+ return False
+
+ # Make sure that each frame is the same
+ for frame1, frame2 in zip(self.iter_frames(), other.iter_frames()):
+ if not np.array_equal(frame1, frame2):
+ return False
+
+ return True
+
# Support the Context Manager protocol, to ensure that resources are cleaned up.
def __enter__(self):
diff --git a/moviepy/editor.py b/moviepy/editor.py
index 96f0eef8..8e5515c3 100644
--- a/moviepy/editor.py
+++ b/moviepy/editor.py
@@ -28,7 +28,7 @@ os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"
from .video.io.VideoFileClip import VideoFileClip
from .video.io.ImageSequenceClip import ImageSequenceClip
from .video.io.downloader import download_webfile
-from .video.VideoClip import VideoClip, ImageClip, ColorClip, TextClip
+from .video.VideoClip import VideoClip, ImageClip, ColorClip, TextClip, BitmapClip
from .video.compositing.CompositeVideoClip import CompositeVideoClip, clips_array
from .video.compositing.concatenate import concatenate_videoclips
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index ab9b6492..667b4989 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -1278,3 +1278,124 @@ class TextClip(ImageClip):
string = string.lower()
names_list = TextClip.list(arg)
return [name for name in names_list if string in name.lower()]
+
+
+class BitmapClip(VideoClip):
+ def __init__(self, bitmap_frames, *, color_dict=None, ismask=False):
+ """
+ Creates a VideoClip object from a bitmap representation. Primarily used in the test suite.
+
+ Parameters
+ -----------
+
+ bitmap_frames
+ A list of frames. Each frame is a list of strings. Each string represents a row of colors.
+ Each color represents an (r, g, b) tuple.
+ Example input (2 frames, 5x3 pixel size):
+ [["RRRRR",
+ "RRBRR",
+ "RRBRR"],
+ ["RGGGR",
+ "RGGGR",
+ "RGGGR"]]
+
+ color_dict
+ A dictionary that can be used to set specific (r, g, b) values that correspond
+ to the letters used in ``bitmap_frames``.
+ eg ``{"A": (50, 150, 150)}``.
+
+ Defaults to
+ ::
+ {
+ "R": (255, 0, 0),
+ "G": (0, 255, 0),
+ "B": (0, 0, 255),
+ "O": (0, 0, 0), # "O" represents black
+ "W": (255, 255, 255),
+ "A": (89, 225, 62), # "A", "C", "D" and "E" represent arbitrary colors
+ "C": (113, 157, 108),
+ "D": (215, 182, 143),
+ "E": (57, 26, 252),
+ }
+
+ ismask
+ Set to ``True`` if the clip is going to be used as a mask.
+
+ """
+ if color_dict:
+ self.color_dict = color_dict
+ else:
+ self.color_dict = {
+ "R": (255, 0, 0),
+ "G": (0, 255, 0),
+ "B": (0, 0, 255),
+ "O": (0, 0, 0),
+ "W": (255, 255, 255),
+ "A": (89, 225, 62),
+ "C": (113, 157, 108),
+ "D": (215, 182, 143),
+ "E": (57, 26, 252),
+ }
+
+ frame_list = []
+ for input_frame in bitmap_frames:
+ output_frame = []
+ for row in input_frame:
+ output_frame.append([self.color_dict[color] for color in row])
+ frame_list.append(np.array(output_frame))
+
+ frame_array = np.array(frame_list)
+ VideoClip.__init__(
+ self, make_frame=lambda t: frame_array[int(t)], ismask=ismask
+ )
+
+ self.total_frames = len(frame_array)
+ self.fps = None
+
+ @convert_to_seconds(["duration"])
+ def set_duration(self, duration, change_end=True):
+ """
+ Sets the ``duration`` attribute of the clip.
+ Additionally, if the clip's ``fps`` attribute has not already been set, it will
+ be set based on the new duration and the total number of frames.
+ """
+ if self.fps is None:
+ return (
+ super()
+ .set_duration(duration=duration, change_end=change_end)
+ .set_fps(int(self.total_frames / duration))
+ )
+
+ return super().set_duration(duration=duration, change_end=change_end)
+
+ def set_fps(self, fps):
+ """
+ Sets the ``fps`` attribute of the clip.
+ Additionally, if the clip's ``duration`` attribute has not already been set, it will
+ be set based on the new fps and the total number of frames.
+ """
+ total_duration = self.total_frames / fps
+ if self.duration is None or self.duration > total_duration:
+ return super().set_fps(fps).set_duration(total_duration)
+ return super().set_fps(fps)
+
+ def to_bitmap(self, color_dict=None):
+ """
+ Returns a valid bitmap list that represents each frame of the clip.
+ If `color_dict` is not specified, then it will use the same `color_dict`
+ that was used to create the clip.
+ """
+ color_dict = color_dict or self.color_dict
+
+ bitmap = []
+ for frame in self.iter_frames():
+ bitmap.append([])
+ for line in frame:
+ bitmap[-1].append("")
+ for pixel in line:
+ letter = list(color_dict.keys())[
+ list(color_dict.values()).index(tuple(pixel))
+ ]
+ bitmap[-1][-1] += letter
+
+ return bitmap
diff --git a/moviepy/video/fx/colorx.py b/moviepy/video/fx/colorx.py
index f1c9e1a4..04846d1f 100644
--- a/moviepy/video/fx/colorx.py
+++ b/moviepy/video/fx/colorx.py
@@ -2,8 +2,9 @@ import numpy as np
def colorx(clip, factor):
- """ multiplies the clip's colors by the given factor, can be used
- to decrease or increase the clip's brightness (is that the
- reight word ?)
+ """
+ Multiplies the clip's colors by the given factor, can be used
+ to decrease or increase the clip's brightness (is that the
+ right word ?)
"""
return clip.fl_image(lambda pic: np.minimum(255, (factor * pic)).astype("uint8"))
diff --git a/moviepy/video/fx/even_size.py b/moviepy/video/fx/even_size.py
index ae5274f6..2a547a01 100644
--- a/moviepy/video/fx/even_size.py
+++ b/moviepy/video/fx/even_size.py
@@ -17,7 +17,7 @@ def even_size(clip):
def fl_image(a):
return a[:-1, :-1, :]
- elif w_even:
+ elif h_even:
def fl_image(a):
return a[:, :-1, :]
diff --git a/moviepy/video/fx/freeze.py b/moviepy/video/fx/freeze.py
index 7d831d77..e163ce53 100644
--- a/moviepy/video/fx/freeze.py
+++ b/moviepy/video/fx/freeze.py
@@ -16,7 +16,7 @@ def freeze(clip, t=0, freeze_duration=None, total_duration=None, padding_end=0):
"""
if t == "end":
- t = clip.duration - padding_end
+ t = clip.duration - padding_end - 1
if freeze_duration is None:
freeze_duration = total_duration - clip.duration
diff --git a/moviepy/video/fx/loop.py b/moviepy/video/fx/loop.py
index ca2b7bcd..4e0d90e5 100644
--- a/moviepy/video/fx/loop.py
+++ b/moviepy/video/fx/loop.py
@@ -4,7 +4,7 @@ from moviepy.decorators import apply_to_audio, apply_to_mask, requires_duration
@requires_duration
@apply_to_mask
@apply_to_audio
-def loop(self, n=None, duration=None):
+def loop(clip, n=None, duration=None):
"""
Returns a clip that plays the current clip in an infinite loop.
Ideal for clips coming from gifs.
@@ -18,9 +18,10 @@ def loop(self, n=None, duration=None):
duration
Total duration of the clip. Can be specified instead of n.
"""
- result = self.fl_time(lambda t: t % self.duration)
+ previous_duration = clip.duration
+ clip = clip.fl_time(lambda t: t % previous_duration)
if n:
- duration = n * self.duration
+ duration = n * previous_duration
if duration:
- result = result.set_duration(duration)
- return result
+ clip = clip.set_duration(duration)
+ return clip
diff --git a/moviepy/video/fx/margin.py b/moviepy/video/fx/margin.py
index 464bac5f..af950430 100644
--- a/moviepy/video/fx/margin.py
+++ b/moviepy/video/fx/margin.py
@@ -41,7 +41,6 @@ def margin(
return bg
if isinstance(clip, ImageClip):
-
im = make_bg(clip.w, clip.h)
im[top : top + clip.h, left : left + clip.w] = clip.img
return clip.fl_image(lambda pic: im)
diff --git a/moviepy/video/fx/rotate.py b/moviepy/video/fx/rotate.py
index 51c36c34..b60485be 100644
--- a/moviepy/video/fx/rotate.py
+++ b/moviepy/video/fx/rotate.py
@@ -22,9 +22,9 @@ except ImportError:
def rotate(clip, angle, unit="deg", resample="bicubic", expand=True):
"""
- Change unit to 'rad' to define angles as radians.
- If the angle is not one of 90, 180, -90, -180 (degrees) there will be
- black borders. You can make them transparent with
+ Rotates the specified clip by ``angle`` degrees (or radians) anticlockwise
+ If the angle is not a multiple of 90 (degrees), the package ``pillow`` must be installed,
+ and there will be black borders. You can make them transparent with
>>> newclip = clip.add_mask().rotate(72)
@@ -38,7 +38,8 @@ def rotate(clip, angle, unit="deg", resample="bicubic", expand=True):
Either a value or a function angle(t) representing the angle of rotation
unit
- Unit of parameter `angle` (either `deg` for degrees or `rad` for radians)
+ Unit of parameter `angle` (either `deg` for degrees or `rad` for radians).
+ Default: `deg`
resample
One of "nearest", "bilinear", or "bicubic".
@@ -46,12 +47,12 @@ def rotate(clip, angle, unit="deg", resample="bicubic", expand=True):
expand
Only applIf False, the clip will maintain the same True, the clip will be resized so that the whole
"""
-
- resample = {
- "bilinear": Image.BILINEAR,
- "nearest": Image.NEAREST,
- "bicubic": Image.BICUBIC,
- }[resample]
+ if PIL_FOUND:
+ resample = {
+ "bilinear": Image.BILINEAR,
+ "nearest": Image.NEAREST,
+ "bicubic": Image.BICUBIC,
+ }[resample]
if not hasattr(angle, "__call__"):
# if angle is a constant, convert to a constant function
@@ -70,17 +71,19 @@ def rotate(clip, angle, unit="deg", resample="bicubic", expand=True):
if unit == "rad":
a = 360.0 * a / (2 * np.pi)
+ a %= 360
+ if (a == 0) and expand:
+ return im
if (a == 90) and expand:
return np.transpose(im, axes=transpo)[::-1]
- elif (a == -90) and expand:
+ elif (a == 270) and expand:
return np.transpose(im, axes=transpo)[:, ::-1]
- elif (a in [180, -180]) and expand:
+ elif (a == 180) and expand:
return im[::-1, ::-1]
elif not PIL_FOUND:
raise ValueError(
- 'Without "Pillow" installed, only angles 90, -90,'
- '180 are supported, please install "Pillow" with'
- "pip install pillow"
+ 'Without "Pillow" installed, only angles that are a multiple of 90'
+ ' are supported, please install "Pillow" with `pip install pillow`'
)
else:
return pil_rotater(im, a, resample=resample, expand=expand)
diff --git a/moviepy/video/fx/scroll.py b/moviepy/video/fx/scroll.py
index e37ad2f9..d2be8af2 100644
--- a/moviepy/video/fx/scroll.py
+++ b/moviepy/video/fx/scroll.py
@@ -1,8 +1,23 @@
def scroll(
- clip, h=None, w=None, x_speed=0, y_speed=0, x_start=0, y_start=0, apply_to="mask"
+ clip, w=None, h=None, x_speed=0, y_speed=0, x_start=0, y_start=0, apply_to="mask"
):
- """ Scrolls horizontally or vertically a clip, e.g. to make end
- credits """
+ """
+ Scrolls horizontally or vertically a clip, e.g. to make end credits
+
+ Parameters
+ -----------
+
+ w, h
+ The width and height of the final clip. Default to clip.w and clip.h
+
+ x_speed, y_speed
+
+ x_start, y_start
+
+
+ apply_to
+
+ """
if h is None:
h = clip.h
if w is None:
diff --git a/moviepy/video/fx/time_mirror.py b/moviepy/video/fx/time_mirror.py
index 1c044e3e..ba4c13e7 100644
--- a/moviepy/video/fx/time_mirror.py
+++ b/moviepy/video/fx/time_mirror.py
@@ -10,4 +10,4 @@ def time_mirror(self):
The clip must have its ``duration`` attribute set.
The same effect is applied to the clip's audio and mask if any.
"""
- return self.fl_time(lambda t: self.duration - t, keep_duration=True)
+ return self.fl_time(lambda t: self.duration - t - 1, keep_duration=True)
diff --git a/tests/test_BitmapClip.py b/tests/test_BitmapClip.py
new file mode 100644
index 00000000..c740075e
--- /dev/null
+++ b/tests/test_BitmapClip.py
@@ -0,0 +1,55 @@
+import pytest
+import numpy as np
+
+from moviepy.video.VideoClip import BitmapClip
+
+
+def test_clip_generation():
+ bitmap = [["RR", "RR"], ["RB", "RB"]]
+ expected_frame_array = np.array(
+ [
+ np.array([[(255, 0, 0), (255, 0, 0)], [(255, 0, 0), (255, 0, 0)]]),
+ np.array([[(255, 0, 0), (0, 0, 255)], [(255, 0, 0), (0, 0, 255)]]),
+ ]
+ )
+ unexpected_frame_array = np.array(
+ [
+ np.array([[(255, 0, 0), (255, 0, 0)], [(255, 0, 0), (255, 0, 1)]]),
+ np.array([[(255, 0, 0), (0, 0, 255)], [(255, 0, 0), (0, 0, 255)]]),
+ ]
+ )
+
+ clip = BitmapClip(bitmap)
+ clip.duration = len(bitmap)
+ clip.fps = 1
+ frame_array = np.array(list(clip.iter_frames()))
+
+ # Check that frame_list == expected_frame_list
+ assert np.array_equal(frame_array, expected_frame_array)
+
+ # Check that frame_list != unexpected_frame_list
+ assert not np.array_equal(frame_array, unexpected_frame_array)
+
+
+def test_set_fps():
+ bitmap = [["R"], ["R"], ["B"], ["B"], ["G"], ["G"]]
+ clip = BitmapClip(bitmap)
+
+ fps_clip = clip.set_fps(1)
+ assert fps_clip.fps == 1
+ assert fps_clip.duration == 6
+
+
+def test_set_duration():
+ bitmap = [["R"], ["R"], ["B"], ["B"], ["G"], ["G"]]
+ clip = BitmapClip(bitmap)
+
+ duration_clip = clip.set_duration(len(bitmap))
+ assert duration_clip.fps == 1
+ assert duration_clip.duration == 6
+
+
+if __name__ == "__main__":
+ test_clip_generation()
+ test_set_fps()
+ test_set_duration()
diff --git a/tests/test_Clip.py b/tests/test_Clip.py
new file mode 100644
index 00000000..c93e0f1f
--- /dev/null
+++ b/tests/test_Clip.py
@@ -0,0 +1,20 @@
+import pytest
+
+from moviepy.video.VideoClip import BitmapClip
+
+
+def test_clip_equality():
+ bitmap = [["RR", "RR"], ["RB", "RB"]]
+ different_bitmap = [["RR", "RB"], ["RB", "RB"]]
+
+ clip = BitmapClip(bitmap).set_fps(1)
+ same_clip = BitmapClip(bitmap).set_fps(1)
+
+ different_clip = BitmapClip(different_bitmap).set_fps(1)
+
+ assert clip == same_clip
+ assert clip != different_clip
+
+
+if __name__ == "__main__":
+ pytest.main()
diff --git a/tests/test_VideoClip.py b/tests/test_VideoClip.py
index 99ad4a6c..69761607 100644
--- a/tests/test_VideoClip.py
+++ b/tests/test_VideoClip.py
@@ -1,18 +1,23 @@
import os
import pytest
-from numpy import pi, sin
+from numpy import pi, sin, array
from moviepy.audio.AudioClip import AudioClip
from moviepy.audio.io.AudioFileClip import AudioFileClip
from moviepy.utils import close_all_clips
from moviepy.video.fx.speedx import speedx
from moviepy.video.io.VideoFileClip import VideoFileClip
-from moviepy.video.VideoClip import ColorClip, VideoClip
+from moviepy.video.VideoClip import ColorClip, BitmapClip
from tests.test_helper import TMP_DIR
+def test_aspect_ratio():
+ clip = BitmapClip([["AAA", "BBB"]])
+ assert clip.aspect_ratio == 1.5
+
+
def test_check_codec():
clip = VideoFileClip("media/big_buck_bunny_432_433.webm")
location = os.path.join(TMP_DIR, "not_a_video.mas")
diff --git a/tests/test_fx.py b/tests/test_fx.py
index f09c56ab..99f5450a 100644
--- a/tests/test_fx.py
+++ b/tests/test_fx.py
@@ -5,12 +5,16 @@ import pytest
from moviepy.audio.fx.audio_normalize import audio_normalize
from moviepy.audio.io.AudioFileClip import AudioFileClip
from moviepy.utils import close_all_clips
+from moviepy.video.VideoClip import BitmapClip, ColorClip
from moviepy.video.fx.blackwhite import blackwhite
from moviepy.video.fx.blink import blink
from moviepy.video.fx.colorx import colorx
from moviepy.video.fx.crop import crop
+from moviepy.video.fx.even_size import even_size
from moviepy.video.fx.fadein import fadein
from moviepy.video.fx.fadeout import fadeout
+from moviepy.video.fx.freeze import freeze
+from moviepy.video.fx.freeze_region import freeze_region
from moviepy.video.fx.invert_colors import invert_colors
from moviepy.video.fx.loop import loop
from moviepy.video.fx.lum_contrast import lum_contrast
@@ -33,7 +37,12 @@ def get_test_video():
return VideoFileClip("media/big_buck_bunny_432_433.webm").subclip(0, 1)
+def test_accel_decel():
+ pass
+
+
def test_blackwhite():
+ # TODO update to use BitmapClip
clip = get_test_video()
clip1 = blackwhite(clip)
clip1.write_videofile(os.path.join(TMP_DIR, "blackwhite1.webm"))
@@ -48,33 +57,59 @@ def test_blackwhite():
def test_colorx():
- clip = get_test_video()
- clip1 = colorx(clip, 2)
- clip1.write_videofile(os.path.join(TMP_DIR, "colorx1.webm"))
- close_all_clips(locals())
+ color_dict = {"H": (0, 0, 200), "L": (0, 0, 50), "B": (0, 0, 255), "O": (0, 0, 0)}
+ clip = BitmapClip([["LLO", "BLO"]], color_dict=color_dict).set_fps(1)
+
+ clipfx = colorx(clip, 4)
+ target = BitmapClip([["HHO", "BHO"]], color_dict=color_dict).set_fps(1)
+ assert target == clipfx
def test_crop():
- clip = get_test_video()
+ # x: 0 -> 4, y: 0 -> 3 inclusive
+ clip = BitmapClip([["ABCDE", "EDCBA", "CDEAB", "BAEDC"]]).set_fps(1)
- clip1 = crop(clip) # ie, no cropping (just tests all default values)
- clip1.write_videofile(os.path.join(TMP_DIR, "crop1.webm"))
+ clip1 = crop(clip)
+ target1 = BitmapClip([["ABCDE", "EDCBA", "CDEAB", "BAEDC"]]).set_fps(1)
+ assert clip1 == target1
- clip2 = crop(clip, x1=50, y1=60, x2=460, y2=275)
- clip2.write_videofile(os.path.join(TMP_DIR, "crop2.webm"))
+ clip2 = crop(clip, x1=1, y1=1, x2=3, y2=3)
+ target2 = BitmapClip([["DC", "DE"]]).set_fps(1)
+ assert clip2 == target2
- clip3 = crop(clip, y1=30) # remove part above y=30
- clip3.write_videofile(os.path.join(TMP_DIR, "crop3.webm"))
+ clip3 = crop(clip, y1=2)
+ target3 = BitmapClip([["CDEAB", "BAEDC"]]).set_fps(1)
+ assert clip3 == target3
- clip4 = crop(clip, x1=10, width=200) # crop a rect that has width=200
- clip4.write_videofile(os.path.join(TMP_DIR, "crop4.webm"))
+ clip4 = crop(clip, x1=2, width=2)
+ target4 = BitmapClip([["CD", "CB", "EA", "ED"]]).set_fps(1)
+ assert clip4 == target4
- clip5 = crop(clip, x_center=300, y_center=400, width=50, height=150)
- clip5.write_videofile(os.path.join(TMP_DIR, "crop5.webm"))
+ # TODO x_center=1 does not perform correctly
+ clip5 = crop(clip, x_center=2, y_center=2, width=3, height=3)
+ target5 = BitmapClip([["ABC", "EDC", "CDE"]]).set_fps(1)
+ assert clip5 == target5
- clip6 = crop(clip, x_center=300, width=400, y1=100, y2=600)
- clip6.write_videofile(os.path.join(TMP_DIR, "crop6.webm"))
- close_all_clips(locals())
+ clip6 = crop(clip, x_center=2, width=2, y1=1, y2=2)
+ target6 = BitmapClip([["DC"]]).set_fps(1)
+ assert clip6 == target6
+
+
+def test_even_size():
+ clip1 = BitmapClip([["ABC", "BCD"]]).set_fps(1) # Width odd
+ clip1even = even_size(clip1)
+ target1 = BitmapClip([["AB", "BC"]]).set_fps(1)
+ assert clip1even == target1
+
+ clip2 = BitmapClip([["AB", "BC", "CD"]]).set_fps(1) # Height odd
+ clip2even = even_size(clip2)
+ target2 = BitmapClip([["AB", "BC"]]).set_fps(1)
+ assert clip2even == target2
+
+ clip3 = BitmapClip([["ABC", "BCD", "CDE"]]).set_fps(1) # Width and height odd
+ clip3even = even_size(clip3)
+ target3 = BitmapClip([["AB", "BC"]]).set_fps(1)
+ assert clip3even == target3
def test_fadein():
@@ -91,25 +126,74 @@ def test_fadeout():
close_all_clips(locals())
+def test_freeze():
+ clip = BitmapClip([["R"], ["G"], ["B"]]).set_fps(1) # 3 separate frames
+
+ clip1 = freeze(clip, t=1, freeze_duration=1)
+ target1 = BitmapClip([["R"], ["G"], ["G"], ["B"]]).set_fps(1)
+ assert clip1 == target1
+
+ clip2 = freeze(clip, t="end", freeze_duration=1)
+ target2 = BitmapClip([["R"], ["G"], ["B"], ["B"]]).set_fps(1)
+ assert clip2 == target2
+
+ clip3 = freeze(clip, t=1, total_duration=4)
+ target3 = BitmapClip([["R"], ["G"], ["G"], ["B"]]).set_fps(1)
+ assert clip3 == target3
+
+ clip4 = freeze(clip, t="end", total_duration=4, padding_end=1)
+ target4 = BitmapClip([["R"], ["G"], ["G"], ["B"]]).set_fps(1)
+ assert clip4 == target4
+
+
+def test_freeze_region():
+ clip = BitmapClip([["AAB", "CCC"], ["BBR", "DDD"], ["CCC", "ABC"]]).set_fps(1)
+
+ # Test region
+ clip1 = freeze_region(clip, t=1, region=(2, 0, 3, 1))
+ target1 = BitmapClip([["AAR", "CCC"], ["BBR", "DDD"], ["CCR", "ABC"]]).set_fps(1)
+ assert clip1 == target1
+
+ # Test outside_region
+ clip2 = freeze_region(clip, t=1, outside_region=(2, 0, 3, 1))
+ target2 = BitmapClip([["BBB", "DDD"], ["BBR", "DDD"], ["BBC", "DDD"]]).set_fps(1)
+ assert clip2 == target2
+
+ pass
+
+
+def test_gamma_corr():
+ pass
+
+
+def test_headblur():
+ pass
+
+
def test_invert_colors():
- clip = get_test_video()
+ clip = BitmapClip(
+ [["AB", "BC"]],
+ color_dict={"A": (0, 0, 0), "B": (50, 100, 150), "C": (255, 255, 255)},
+ ).set_fps(1)
+
clip1 = invert_colors(clip)
- clip1.write_videofile(os.path.join(TMP_DIR, "invert_colors1.webm"))
- close_all_clips(locals())
+ target1 = BitmapClip(
+ [["CD", "DA"]],
+ color_dict={"A": (0, 0, 0), "D": (205, 155, 105), "C": (255, 255, 255)},
+ ).set_fps(1)
+ assert clip1 == target1
def test_loop():
- # these do not work.. what am I doing wrong??
- return
-
clip = get_test_video()
- clip1 = clip.loop() # infinite looping
+ clip1 = loop(clip).set_duration(3) # infinite looping
clip1.write_videofile(os.path.join(TMP_DIR, "loop1.webm"))
- clip2 = clip.loop(duration=10) # loop for 10 seconds
+ return # Still buggy. TODO fix
+ clip2 = loop(clip, duration=10) # loop for 10 seconds
clip2.write_videofile(os.path.join(TMP_DIR, "loop2.webm"))
- clip3 = clip.loop(n=3) # loop 3 times
+ clip3 = loop(clip, n=3) # loop 3 times
clip3.write_videofile(os.path.join(TMP_DIR, "loop3.webm"))
close_all_clips(objects=locals())
@@ -133,16 +217,25 @@ def test_make_loopable():
def test_margin():
- clip = get_test_video()
- clip1 = margin(clip) # does the default values change anything?
- clip1.write_videofile(os.path.join(TMP_DIR, "margin1.webm"))
+ clip = BitmapClip([["RRR", "RRR"], ["RRB", "RRB"]]).set_fps(1)
- clip2 = margin(clip, mar=100) # all margins are 100px
- clip2.write_videofile(os.path.join(TMP_DIR, "margin2.webm"))
+ # Make sure that the default values leave clip unchanged
+ clip1 = margin(clip)
+ assert clip == clip1
- clip3 = margin(clip, mar=100, color=(255, 0, 0)) # red margin
- clip3.write_videofile(os.path.join(TMP_DIR, "margin3.webm"))
- close_all_clips(locals())
+ # 1 pixel black margin
+ clip2 = margin(clip, mar=1)
+ target = BitmapClip(
+ [["OOOOO", "ORRRO", "ORRRO", "OOOOO",], ["OOOOO", "ORRBO", "ORRBO", "OOOOO",],]
+ ).set_fps(1)
+ assert target == clip2
+
+ # 1 pixel green margin
+ clip3 = margin(clip, mar=1, color=(0, 255, 0))
+ target = BitmapClip(
+ [["GGGGG", "GRRRG", "GRRRG", "GGGGG",], ["GGGGG", "GRRBG", "GRRBG", "GGGGG",],]
+ ).set_fps(1)
+ assert target == clip3
def test_mask_and():
@@ -158,17 +251,17 @@ def test_mask_or():
def test_mirror_x():
- clip = get_test_video()
+ clip = BitmapClip([["AB", "CD"]]).set_fps(1)
clip1 = mirror_x(clip)
- clip1.write_videofile(os.path.join(TMP_DIR, "mirror_x1.webm"))
- close_all_clips(locals())
+ target = BitmapClip([["BA", "DC"]]).set_fps(1)
+ assert clip1 == target
def test_mirror_y():
- clip = get_test_video()
+ clip = BitmapClip([["AB", "CD"]]).set_fps(1)
clip1 = mirror_y(clip)
- clip1.write_videofile(os.path.join(TMP_DIR, "mirror_y1.webm"))
- close_all_clips(locals())
+ target = BitmapClip([["CD", "AB"]]).set_fps(1)
+ assert clip1 == target
def test_painting():
@@ -176,6 +269,7 @@ def test_painting():
def test_resize():
+ # TODO update to use BitmapClip
clip = get_test_video()
clip1 = resize(clip, (460, 720)) # New resolution: (460,720)
@@ -197,55 +291,94 @@ def test_resize():
# clip4.write_videofile(os.path.join(TMP_DIR, "resize4.webm"))
-def test_rotate():
- clip = get_test_video()
[email protected]("angle_offset", [-360, 0, 360, 720])
+def test_rotate(angle_offset):
+ # Run several times to ensure that adding 360 to rotation angles has no effect
+ clip = BitmapClip([["AAAA", "BBBB", "CCCC"], ["ABCD", "BCDE", "CDEA"]]).set_fps(1)
- clip1 = rotate(clip, 90) # rotate 90 degrees
- assert clip1.size == (clip.size[1], clip.size[0])
- clip1.write_videofile(os.path.join(TMP_DIR, "rotate1.webm"))
+ clip1 = rotate(clip, 0 + angle_offset)
+ target1 = BitmapClip([["AAAA", "BBBB", "CCCC"], ["ABCD", "BCDE", "CDEA"]]).set_fps(
+ 1
+ )
+ assert clip1 == target1
- clip2 = rotate(clip, 180) # rotate 90 degrees
- assert clip2.size == tuple(clip.size)
- clip2.write_videofile(os.path.join(TMP_DIR, "rotate2.webm"))
+ clip2 = rotate(clip, 90 + angle_offset)
+ target2 = BitmapClip(
+ [["ABC", "ABC", "ABC", "ABC"], ["DEA", "CDE", "BCD", "ABC"]]
+ ).set_fps(1)
+ assert clip2 == target2, clip2.to_bitmap()
- clip3 = rotate(clip, 270) # rotate 90 degrees
- assert clip3.size == (clip.size[1], clip.size[0])
- clip3.write_videofile(os.path.join(TMP_DIR, "rotate3.webm"))
+ clip3 = rotate(clip, 180 + angle_offset)
+ target3 = BitmapClip([["CCCC", "BBBB", "AAAA"], ["AEDC", "EDCB", "DCBA"]]).set_fps(
+ 1
+ )
+ assert clip3 == target3
- clip4 = rotate(clip, 360) # rotate 90 degrees
- assert clip4.size == tuple(clip.size)
- clip4.write_videofile(os.path.join(TMP_DIR, "rotate4.webm"))
+ clip4 = rotate(clip, 270 + angle_offset)
+ target4 = BitmapClip(
+ [["CBA", "CBA", "CBA", "CBA"], ["CBA", "DCB", "EDC", "AED"]]
+ ).set_fps(1)
+ assert clip4 == target4
- clip5 = rotate(clip, 50)
- clip5.write_videofile(os.path.join(TMP_DIR, "rotate5.webm"))
+def test_rotate_nonstandard_angles():
# Test rotate with color clip
clip = ColorClip([600, 400], [150, 250, 100]).set_duration(1).set_fps(5)
clip = rotate(clip, 20)
clip.write_videofile(os.path.join(TMP_DIR, "color_rotate.webm"))
- close_all_clips(locals())
-
def test_scroll():
pass
def test_speedx():
- clip = get_test_video()
-
- clip1 = speedx(clip, factor=0.5) # 1/2 speed
- assert clip1.duration == 2
- clip1.write_videofile(os.path.join(TMP_DIR, "speedx1.webm"))
-
- clip2 = speedx(clip, final_duration=2) # 1/2 speed
- assert clip2.duration == 2
- clip2.write_videofile(os.path.join(TMP_DIR, "speedx2.webm"))
-
- clip2 = speedx(clip, final_duration=3) # 1/2 speed
- assert clip2.duration == 3
- clip2.write_videofile(os.path.join(TMP_DIR, "speedx3.webm"))
- close_all_clips(locals())
+ clip = BitmapClip([["A"], ["B"], ["C"], ["D"]]).set_fps(1)
+
+ clip1 = speedx(clip, 0.5) # 1/2x speed
+ target1 = BitmapClip(
+ [["A"], ["A"], ["B"], ["B"], ["C"], ["C"], ["D"], ["D"]]
+ ).set_fps(1)
+ assert clip1 == target1
+
+ clip2 = speedx(clip, final_duration=8) # 1/2x speed
+ target2 = BitmapClip(
+ [["A"], ["A"], ["B"], ["B"], ["C"], ["C"], ["D"], ["D"]]
+ ).set_fps(1)
+ assert clip2 == target2
+
+ clip3 = speedx(clip, final_duration=12) # 1/2x speed
+ target3 = BitmapClip(
+ [
+ ["A"],
+ ["A"],
+ ["A"],
+ ["B"],
+ ["B"],
+ ["B"],
+ ["C"],
+ ["C"],
+ ["C"],
+ ["D"],
+ ["D"],
+ ["D"],
+ ]
+ ).set_fps(1)
+ assert clip3 == target3
+
+ clip4 = speedx(clip, 2) # 2x speed
+ target4 = BitmapClip([["A"], ["C"]]).set_fps(1)
+ assert clip4 == target4
+
+ clip5 = speedx(clip, final_duration=2) # 2x speed
+ target5 = BitmapClip([["A"], ["C"]]).set_fps(1)
+ assert clip5 == target5
+
+ clip6 = speedx(clip, 4) # 4x speed
+ target6 = BitmapClip([["A"]]).set_fps(1)
+ assert (
+ clip6 == target6
+ ), f"{clip6.duration} {target6.duration} {clip6.fps} {target6.fps}"
def test_supersample():
@@ -253,20 +386,38 @@ def test_supersample():
def test_time_mirror():
- clip = get_test_video()
+ clip = BitmapClip([["AA", "AA"], ["BB", "BB"], ["CC", "CC"]]).set_fps(1)
clip1 = time_mirror(clip)
- assert clip1.duration == clip.duration
- clip1.write_videofile(os.path.join(TMP_DIR, "time_mirror1.webm"))
- close_all_clips(locals())
+ target1 = BitmapClip([["CC", "CC"], ["BB", "BB"], ["AA", "AA"]]).set_fps(1)
+ assert clip1 == target1
+
+ clip2 = BitmapClip(
+ [["AA", "AA"], ["BB", "BB"], ["CC", "CC"], ["DD", "DD"]]
+ ).set_fps(1)
+
+ clip3 = time_mirror(clip2)
+ target3 = BitmapClip(
+ [["DD", "DD"], ["CC", "CC"], ["BB", "BB"], ["AA", "AA"]]
+ ).set_fps(1)
+ assert clip3 == target3
def test_time_symmetrize():
- clip = get_test_video()
+ clip = BitmapClip([["AA", "AA"], ["BB", "BB"], ["CC", "CC"]]).set_fps(1)
clip1 = time_symmetrize(clip)
- clip1.write_videofile(os.path.join(TMP_DIR, "time_symmetrize1.webm"))
- close_all_clips(locals())
+ target1 = BitmapClip(
+ [
+ ["AA", "AA"],
+ ["BB", "BB"],
+ ["CC", "CC"],
+ ["CC", "CC"],
+ ["BB", "BB"],
+ ["AA", "AA"],
+ ]
+ ).set_fps(1)
+ assert clip1 == target1
def test_normalize():