Skip to content

Video editing with Python

Add tests and documentation for interpolators (#1606)

Álvaro Mondéjar471566b33502
diff --git a/moviepy/video/tools/interpolators.py b/moviepy/video/tools/interpolators.py
index f1e83246..4723e88d 100644
--- a/moviepy/video/tools/interpolators.py
+++ b/moviepy/video/tools/interpolators.py
@@ -1,12 +1,41 @@
-"""Classes for easy interpolation of trajectories and curves.
-Requires Scipy installed.
-"""
+"""Classes for easy interpolation of trajectories and curves."""
import numpy as np
class Interpolator:
- """Poorman's linear interpolator, doesn't require Scipy."""
+ """Poorman's linear interpolator.
+
+ Parameters
+ ----------
+
+ tt : list, optional
+ List of time frames for the interpolator.
+
+ ss : list, optional
+ List of values for the interpolator.
+
+ ttss : list, optional
+ Lists of time frames and their correspondients values for the
+ interpolator. This argument can be used instead of ``tt`` and ``ss``
+ to instanciate the interpolator using an unique argument.
+
+ left : float, optional
+ Value to return when ``t < tt[0]``.
+
+ right : float, optional
+ Value to return when ``t > tt[-1]``.
+
+
+ Examples
+ --------
+
+ >>> # instanciate using `tt` and `ss`
+ >>> interpolator = Interpolator(tt=[0, 1, 2], ss=[3, 4, 5])
+ >>>
+ >>> # instanciate using `ttss`
+ >>> interpolator = Interpolator(ttss=[[0, 3], [1, 4], [2, 5]]) # [t, value]
+ """
def __init__(self, tt=None, ss=None, ttss=None, left=None, right=None):
@@ -20,12 +49,43 @@ class Interpolator:
self.tmin, self.tmax = min(tt), max(tt)
def __call__(self, t):
- """TODO: needs documentation"""
+ """Interpolates ``t``.
+
+ Parameters
+ ----------
+
+ t : float
+ Time frame for which the correspondent value will be returned.
+ """
return np.interp(t, self.tt, self.ss, self.left, self.right)
class Trajectory:
- """TODO: needs documentation"""
+ """Trajectory compound by time frames and (x, y) pixels.
+
+ It's designed as an interpolator, so you can get the position at a given
+ time ``t``. You can instanciate it from a file using the methods
+ ``from_file`` and ``load_list``.
+
+
+ Parameters
+ ----------
+
+ tt : list or numpy.ndarray
+ Time frames.
+
+ xx : list or numpy.ndarray
+ X positions in the trajectory.
+
+ yy : list or numpy.ndarray
+ Y positions in the trajectory.
+
+
+ Examples
+ --------
+
+ >>> trajectory = Trajectory([0, .166, .333], [554, 474, 384], [100, 90, 91])
+ """
def __init__(self, tt, xx, yy):
@@ -35,40 +95,115 @@ class Trajectory:
self.update_interpolators()
def __call__(self, t):
- """TODO: needs documentation"""
+ """Interpolates the trajectory at the given time ``t``.
+
+ Parameters
+ ----------
+
+ t : float
+ Time for which to the corresponding position will be returned.
+ """
return np.array([self.xi(t), self.yi(t)])
def addx(self, x):
- """TODO: needs documentation"""
+ """Adds a value to the ``xx`` position of the trajectory.
+
+ Parameters
+ ----------
+
+ x : int
+ Value added to ``xx`` in the trajectory.
+
+
+ Returns
+ -------
+
+ Trajectory : new instance with the new X position included.
+ """
return Trajectory(self.tt, self.xx + x, self.yy)
def addy(self, y):
- """TODO: needs documentation"""
+ """Adds a value to the ``yy`` position of the trajectory.
+
+ Parameters
+ ----------
+
+ y : int
+ Value added to ``yy`` in the trajectory.
+
+
+ Returns
+ -------
+
+ Trajectory : new instance with the new Y position included.
+ """
return Trajectory(self.tt, self.xx, self.yy + y)
def update_interpolators(self):
- """TODO: needs documentation"""
+ """Updates the internal X and Y position interpolators for the instance."""
self.xi = Interpolator(self.tt, self.xx)
self.yi = Interpolator(self.tt, self.yy)
def txy(self, tms=False):
- """TODO: needs documentation"""
+ """Returns all times with the X and Y values of each position.
+
+ Parameters
+ ----------
+
+ tms : bool, optional
+ If is ``True``, the time will be returned in milliseconds.
+ """
return zip((1000 if tms else 1) * self.tt, self.xx, self.yy)
def to_file(self, filename):
- """TODO: needs documentation"""
- np.savetxt(filename, np.array(self.txy(tms=True)), fmt="%d", delimiter="\t")
+ """Saves the trajectory data in a text file.
+
+ Parameters
+ ----------
+
+ filename : str
+ Path to the location of the new trajectory text file.
+ """
+ np.savetxt(
+ filename,
+ np.array(list(self.txy(tms=True))),
+ fmt="%d",
+ delimiter="\t",
+ )
@staticmethod
def from_file(filename):
- """TODO: needs documentation"""
+ """Instanciates an object of Trajectory using a data text file.
+
+ Parameters
+ ----------
+
+ filename : str
+ Path to the location of trajectory text file to load.
+
+
+ Returns
+ -------
+
+ Trajectory : new instance loaded from text file.
+ """
arr = np.loadtxt(filename, delimiter="\t")
tt, xx, yy = arr.T
return Trajectory(1.0 * tt / 1000, xx, yy)
@staticmethod
def save_list(trajs, filename):
- """TODO: needs documentation"""
+ """Saves a set of trajectories into a text file.
+
+ Parameters
+ ----------
+
+ trajs : list
+ List of trajectories to be saved.
+
+ filename : str
+ Path of the text file that will store the trajectories data.
+ """
N = len(trajs)
arr = np.hstack([np.array(list(t.txy(tms=True))) for t in trajs])
np.savetxt(
@@ -81,7 +216,20 @@ class Trajectory:
@staticmethod
def load_list(filename):
- """TODO: needs documentation"""
+ """Loads a list of trajectories from a data text file.
+
+ Parameters
+ ----------
+
+ filename : str
+ Path of the text file that stores the data of a set of trajectories.
+
+
+ Returns
+ -------
+
+ list : List of trajectories loaded from the file.
+ """
arr = np.loadtxt(filename, delimiter="\t").T
Nlines = arr.shape[0]
return [
diff --git a/tests/test_videotools.py b/tests/test_videotools.py
index c9a00e84..c84e4481 100644
--- a/tests/test_videotools.py
+++ b/tests/test_videotools.py
@@ -24,6 +24,7 @@ from moviepy.video.tools.cuts import (
find_video_period,
)
from moviepy.video.tools.drawing import circle, color_gradient, color_split
+from moviepy.video.tools.interpolators import Interpolator, Trajectory
from moviepy.video.VideoClip import BitmapClip, ColorClip, ImageClip, VideoClip
from tests.test_helper import FONT, TMP_DIR, get_mono_wave, get_stereo_wave
@@ -814,6 +815,113 @@ def test_color_split(
assert np.array_equal(result, expected_result)
+ ("ttss", "tt", "ss", "left", "right", "interpolation_results"),
+ (
+ pytest.param(
+ [[0, 3], [1, 4], [2, 5]],
+ None,
+ None,
+ -1,
+ 6,
+ {
+ 3: 6,
+ 4: 6, # right
+ -1: -1,
+ -2: -1, # left
+ 1: 4,
+ 2: 5, # values
+ },
+ id="ttss",
+ ),
+ pytest.param(
+ None,
+ [0, 1, 2],
+ [3, 4, 5],
+ -1,
+ 39,
+ {
+ 3: 39,
+ 4: 39, # right
+ -1: -1,
+ -2: -1, # left
+ 1: 4,
+ 2: 5, # values
+ },
+ id="tt-ss",
+ ),
+ ),
+)
+def test_Interpolator(ttss, tt, ss, left, right, interpolation_results):
+ interpolator = Interpolator(ttss=ttss, tt=tt, ss=ss, left=left, right=right)
+ for value, expected_result in interpolation_results.items():
+ assert interpolator(value) == expected_result
+
+
+ ("tt", "xx", "yy", "interpolation_results"),
+ (
+ pytest.param(
+ [0, 1, 2],
+ [0, 2, 3],
+ [0, 2, 3],
+ {0.5: [1, 1], 1: [2, 2], 4: [3, 3], -1: [0, 0]},
+ id="simple",
+ ),
+ pytest.param(
+ [0, 1, 2],
+ [0, -5, -3],
+ [-2, 2, -5],
+ {0.5: [-2.5, 0], 1: [-5, 2], 4: [-3, -5], -1: [0, -2]},
+ id="negative",
+ ),
+ ),
+)
+def test_Trajectory(tt, xx, yy, interpolation_results):
+ trajectory = Trajectory(tt, xx, yy)
+ for value, expected_result in interpolation_results.items():
+ assert np.array_equal(trajectory(value), np.array(expected_result))
+
+
+def test_Trajectory_addx():
+ trajectory = Trajectory([0, 1], [0], [0, 1]).addx(1)
+ assert len(trajectory.xx) == 1
+ assert trajectory.xx[0] == 1
+
+
+def test_Trajectory_addy():
+ trajectory = Trajectory([0, 1], [0], [0, 1]).addy(1)
+ assert len(trajectory.yy) == 2
+ assert trajectory.yy[0] == 1
+ assert trajectory.yy[1] == 2
+
+
+def test_Trajectory_from_to_file():
+ filename = os.path.join(TMP_DIR, "moviepy_Trajectory_from_to_file.txt")
+ if os.path.isfile(filename):
+ os.remove(filename)
+
+ trajectory_file_content = """# t(ms) x y
+0 554 100
+166 474 90
+333 384 91
+"""
+
+ with open(filename, "w") as f:
+ f.write(trajectory_file_content)
+
+ trajectory = Trajectory.from_file(filename)
+
+ assert np.array_equal(trajectory.xx, np.array([554, 474, 384]))
+ assert np.array_equal(trajectory.yy, np.array([100, 90, 91]))
+ assert np.array_equal(trajectory.tt, np.array([0, 0.166, 0.333]))
+
+ trajectory.to_file(filename)
+
+ with open(filename, "r") as f:
+ assert f.read() == "\n".join(trajectory_file_content.split("\n")[1:])
+
+
@pytest.mark.parametrize(
("clip", "filetype", "fps", "maxduration", "t", "expected_error"),
(