Skip to content

Video editing with Python

Add tests for FramesMatches (#1588)

Álvaro Mondéjard213793576d0
diff --git a/moviepy/video/tools/cuts.py b/moviepy/video/tools/cuts.py
index ab1e216e..4c0e2dad 100644
--- a/moviepy/video/tools/cuts.py
+++ b/moviepy/video/tools/cuts.py
@@ -46,23 +46,22 @@ def find_video_period(clip, fps=None, start_time=0.3):
class FramesMatch:
- """
+ """Frames match inside a set of frames.
Parameters
----------
- start_time
- Starting time
+ start_time : float
+ Starting time.
- end_time
- End time
+ end_time : float
+ End time.
- min_distance
+ min_distance : float
Lower bound on the distance between the first and last frames
- max_distance
+ max_distance : float
Upper bound on the distance between the first and last frames
-
"""
def __init__(self, start_time, end_time, min_distance, max_distance):
@@ -72,8 +71,7 @@ class FramesMatch:
self.max_distance = max_distance
self.time_span = end_time - start_time
- def __str__(self):
-
+ def __str__(self): # pragma: no cover
return "(%.04f, %.04f, %.04f, %.04f)" % (
self.start_time,
self.end_time,
@@ -81,22 +79,35 @@ class FramesMatch:
self.max_distance,
)
- def __repr__(self):
- return "(%.04f, %.04f, %.04f, %.04f)" % (
- self.start_time,
- self.end_time,
- self.min_distance,
- self.max_distance,
- )
+ def __repr__(self): # pragma: no cover
+ return self.__str__()
- def __iter__(self):
+ def __iter__(self): # pragma: no cover
return iter(
(self.start_time, self.end_time, self.min_distance, self.max_distance)
)
+ def __eq__(self, other):
+ return (
+ other.start_time == self.start_time
+ and other.end_time == self.end_time
+ and other.min_distance == self.min_distance
+ and other.max_distance == self.max_distance
+ )
+
class FramesMatches(list):
- """TODO: needs documentation"""
+ """Frames matches inside a set of frames.
+
+ You can instanciate it passing a list of FramesMatch objects or
+ using the class methods ``load`` and ``from_clip``.
+
+ Parameters
+ ----------
+
+ lst : list
+ Iterable of FramesMatch objects.
+ """
def __init__(self, lst):
list.__init__(self, sorted(lst, key=lambda e: e.max_distance))
@@ -108,9 +119,15 @@ class FramesMatches(list):
return self[0] if n == 1 else FramesMatches(self[:n])
def filter(self, condition):
- """Returns a FramesMatches object obtained by filtering out the FramesMatch
- which do not satistify the condition ``condition``. ``condition``
- is a function (FrameMatch -> bool).
+ """Return a FramesMatches object obtained by filtering out the
+ FramesMatch which do not satistify a condition.
+
+ Parameters
+ ----------
+
+ condition : func
+ Function which takes a FrameMatch object as parameter and returns a
+ bool.
Examples
--------
@@ -120,7 +137,14 @@ class FramesMatches(list):
return FramesMatches(filter(condition, self))
def save(self, filename):
- """TODO: needs documentation"""
+ """Save a FramesMatches object to a file.
+
+ Parameters
+ ----------
+
+ filename : str
+ Path to the file in which will be dumped the FramesMatches object data.
+ """
np.savetxt(
filename,
np.array([np.array(list(e)) for e in self]),
@@ -130,7 +154,13 @@ class FramesMatches(list):
@staticmethod
def load(filename):
- """Loads a FramesMatches object from a file.
+ """Load a FramesMatches object from a file.
+
+ Parameters
+ ----------
+
+ filename : str
+ Path to the file to use loading a FramesMatches object.
Examples
--------
@@ -141,45 +171,49 @@ class FramesMatches(list):
return FramesMatches(mfs)
@staticmethod
- def from_clip(clip, distance_threshold, max_duration, fps=None):
- """Finds all the frames tht look alike in a clip, for instance to make a
- looping gif.
+ def from_clip(clip, distance_threshold, max_duration, fps=None, logger="bar"):
+ """Finds all the frames that look alike in a clip, for instance to make
+ a looping GIF.
+
+ Parameters
+ ----------
+
+ clip : moviepy.video.VideoClip.VideoClip
+ A MoviePy video clip.
+
+ distance_threshold : float
+ Distance above which a match is rejected.
- This teturns a FramesMatches object of the all pairs of frames with
- (end_time-start_time < max_duration) and whose distance is under
- distance_threshold.
+ max_duration : float
+ Maximal duration (in seconds) between two matching frames.
- This is well optimized routine and quite fast.
+ fps : int, optional
+ Frames per second (default will be ``clip.fps``).
+
+ logger : str, optional
+ Either ``"bar"`` for progress bar or ``None`` or any Proglog logger.
+
+ Returns
+ -------
+
+ FramesMatches
+ All pairs of frames with ``end_time - start_time < max_duration``
+ and whose distance is under ``distance_threshold``.
Examples
--------
- We find all matching frames in a given video and turn the best match with
- a duration of 1.5s or more into a GIF:
+ We find all matching frames in a given video and turn the best match
+ with a duration of 1.5 seconds or more into a GIF:
>>> from moviepy import VideoFileClip
>>> from moviepy.video.tools.cuts import FramesMatches
>>> clip = VideoFileClip("foo.mp4").resize(width=200)
- >>> matches = FramesMatches.from_clip(clip, distance_threshold=10,
- ... max_duration=3) # will take time
+ >>> matches = FramesMatches.from_clip(
+ ... clip, distance_threshold=10, max_duration=3, # will take time
+ ... )
>>> best = matches.filter(lambda m: m.time_span > 1.5).best()
>>> clip.subclip(best.start_time, best.end_time).write_gif("foo.gif")
-
- Parameters
- ----------
-
- clip
- A MoviePy video clip, possibly transformed/resized
-
- distance_threshold
- Distance above which a match is rejected
-
- max_duration
- Maximal duration (in seconds) between two matching frames
-
- fps
- Frames per second (default will be clip.fps)
-
"""
N_pixels = clip.w * clip.h * 3
@@ -195,7 +229,7 @@ class FramesMatches(list):
matching_frames = [] # the final result.
- for (t, frame) in clip.iter_frames(with_times=True, logger="bar"):
+ for (t, frame) in clip.iter_frames(with_times=True, logger=logger):
flat_frame = 1.0 * frame.flatten()
F_norm_sq = dot_product(flat_frame, flat_frame)
@@ -362,7 +396,7 @@ def detect_scenes(
between consecutive frames.
logger
- Either "bar" for progress bar or None or any Proglog logger.
+ Either ``"bar"`` for progress bar or ``None`` or any Proglog logger.
fps
Must be provided if you provide no clip or a clip without
diff --git a/tests/test_videotools.py b/tests/test_videotools.py
index b08d300e..2b583dfc 100644
--- a/tests/test_videotools.py
+++ b/tests/test_videotools.py
@@ -1,12 +1,20 @@
"""Video file clip tests meant to be run with pytest."""
+import math
import os
+import pytest
+
from moviepy.video.compositing.concatenate import concatenate_videoclips
from moviepy.video.io.VideoFileClip import VideoFileClip
from moviepy.video.tools.credits import CreditsClip
-from moviepy.video.tools.cuts import detect_scenes, find_video_period
-from moviepy.video.VideoClip import ColorClip
+from moviepy.video.tools.cuts import (
+ FramesMatch,
+ FramesMatches,
+ detect_scenes,
+ find_video_period,
+)
+from moviepy.video.VideoClip import BitmapClip, ColorClip
from tests.test_helper import FONT, TMP_DIR
@@ -39,7 +47,7 @@ def test_credits():
file_location, 600, gap=100, stroke_color="blue", stroke_width=5, font=FONT
)
image = image.with_duration(3)
- image.write_videofile(vid_location, fps=24)
+ image.write_videofile(vid_location, fps=24, logger=None)
assert image.mask
assert os.path.isfile(vid_location)
@@ -62,5 +70,151 @@ def test_find_video_period():
assert round(find_video_period(clip, fps=70), 6) == 0.5
+ ("bitmap", "distance_threshold", "max_duration", "expected_matches"),
+ (
+ pytest.param(
+ [
+ ["RRR", "GGG", "BBB"],
+ ["WWW", "WWW", "WWW"],
+ ["WWW", "WWW", "WWW"],
+ ["WWW", "WWW", "WWW"],
+ ["RRR", "GGG", "BBB"],
+ ["RRR", "GGG", "BBB"],
+ ["WWW", "WWW", "WWW"],
+ ["RRR", "GGG", "BBB"],
+ ["WWW", "WWW", "WWW"],
+ ],
+ 1,
+ math.inf,
+ [
+ (1, 2, 0, 0),
+ (1, 3, 0, 0),
+ (2, 3, 0, 0),
+ (0, 4, 0, 0),
+ (0, 5, 0, 0),
+ (4, 5, 0, 0),
+ (1, 6, 0, 0),
+ (2, 6, 0, 0),
+ (3, 6, 0, 0),
+ (0, 7, 0, 0),
+ (4, 7, 0, 0),
+ (5, 7, 0, 0),
+ (1, 8, 0, 0),
+ (2, 8, 0, 0),
+ (3, 8, 0, 0),
+ (6, 8, 0, 0),
+ ],
+ id="distance_threshold=1-max_duration=math.inf",
+ ),
+ pytest.param(
+ [
+ ["RRR", "GGG", "BBB"],
+ ["WWW", "WWW", "WWW"],
+ ["WWW", "WWW", "WWW"],
+ ["WWW", "WWW", "WWW"],
+ ["RRR", "GGG", "BBB"],
+ ["RRR", "GGG", "BBB"],
+ ["WWW", "WWW", "WWW"],
+ ["RRR", "GGG", "BBB"],
+ ["WWW", "WWW", "WWW"],
+ ],
+ 1,
+ 2,
+ [
+ (1, 2, 0, 0),
+ (1, 3, 0, 0),
+ (2, 3, 0, 0),
+ (4, 5, 0, 0),
+ (5, 7, 0, 0),
+ (6, 8, 0, 0),
+ ],
+ id="distance_threshold=1-max_duration=2",
+ ),
+ pytest.param(
+ [
+ ["RRR", "GGG", "BBB"],
+ ["RRR", "GGG", "BBR"],
+ ["RRR", "GGG", "BBB"],
+ ["RRR", "GGG", "BRR"],
+ ],
+ 70,
+ 2,
+ [
+ (0, 2, 0, 0),
+ (0, 1, 69.4022, 69.4022),
+ (1, 2, 69.4022, 69.4022),
+ (1, 3, 69.4022, 69.4022),
+ ],
+ id="distance_threshold=70-max_duration=2",
+ ),
+ ),
+)
+def test_FramesMatches_from_clip(
+ bitmap,
+ expected_matches,
+ distance_threshold,
+ max_duration,
+):
+ clip = BitmapClip(bitmap, fps=1)
+
+ matching_frames = FramesMatches.from_clip(
+ clip,
+ distance_threshold,
+ max_duration,
+ logger=None,
+ )
+
+ assert matching_frames
+ assert isinstance(matching_frames, FramesMatches)
+ assert isinstance(matching_frames[0], FramesMatch)
+
+ for i, match in enumerate(matching_frames):
+ for j, n in enumerate(match):
+ assert round(n, 4) == expected_matches[i][j]
+
+
+def test_FramesMatches_filter():
+ input_matching_frames = [
+ FramesMatch(1, 2, 0, 0),
+ FramesMatch(1, 2, 0.8, 0.8),
+ FramesMatch(1, 2, 0.8, 0),
+ ]
+ expected_matching_frames = [FramesMatch(1, 2, 0, 0)]
+ matching_frames_filter = lambda x: not x.min_distance and not x.max_distance
+
+ matching_frames = FramesMatches(input_matching_frames).filter(
+ matching_frames_filter
+ )
+
+ assert len(matching_frames) == len(expected_matching_frames)
+ for i, frames_match in enumerate(matching_frames):
+ assert frames_match == expected_matching_frames[i]
+
+
+def test_FramesMatches_save_load():
+ input_matching_frames = [
+ FramesMatch(1, 2, 0, 0),
+ FramesMatch(1, 2, 0.8, 0),
+ FramesMatch(1, 2, 0.8, 0.8),
+ ]
+ expected_frames_matches_file_content = """1.000 2.000 0.000 0.000
+1.000 2.000 0.800 0.000
+1.000 2.000 0.800 0.800
+"""
+
+ outputfile = os.path.join(TMP_DIR, "moviepy_FramesMatches_save_load.txt")
+
+ # save
+ FramesMatches(input_matching_frames).save(outputfile)
+
+ with open(outputfile, "r") as f:
+ assert f.read() == expected_frames_matches_file_content
+
+ # load
+ for i, frames_match in enumerate(FramesMatches.load(outputfile)):
+ assert frames_match == input_matching_frames[i]
+
+
if __name__ == "__main__":
test_credits()