Video editing with Python
Fix a bad indentation in audio ffmpeg reader + remove scipy and skimage dependency, simplifying resize but removing segmenting
osaajani97257331051b
diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.pyindex 309469e3..a25bbbde 100644--- a/moviepy/audio/io/readers.py+++ b/moviepy/audio/io/readers.py@@ -187,74 +187,74 @@ class FFMPEG_AudioReader:# last case standing: pos = current posself.pos = pos- def get_frame(self, tt):- """Retrieves the audio frame(s) corresponding to the given timestamp(s).-- Parameters- ------------- tt (float or numpy.ndarray): The timestamp(s) at which to retrieve the audio frame(s).- If `tt` is a single float value, the frame corresponding to that timestamp is returned.- If `tt` is a NumPy array of timestamps, an array of frames corresponding to each timestamp is returned.- """- if isinstance(tt, np.ndarray):- # lazy implementation, but should not cause problems in- # 99.99 % of the cases-- # elements of t that are actually in the range of the- # audio file.- in_time = (tt >= 0) & (tt < self.duration)-- # Check that the requested time is in the valid range- if not in_time.any():- raise IOError(- "Error in file %s, " % (self.filename)- + "Accessing time t=%.02f-%.02f seconds, " % (tt[0], tt[-1])- + "with clip duration=%f seconds, " % self.duration- )-- # The np.round in the next line is super-important.- # Removing it results in artifacts in the noise.- frames = np.round((self.fps * tt)).astype(int)[in_time]- fr_min, fr_max = frames.min(), frames.max()-- if not (0 <= (fr_min - self.buffer_startframe) < len(self.buffer)):- self.buffer_around(fr_min)- elif not (0 <= (fr_max - self.buffer_startframe) < len(self.buffer)):- self.buffer_around(fr_max)-- try:- result = np.zeros((len(tt), self.nchannels))- indices = frames - self.buffer_startframe- result[in_time] = self.buffer[indices]- return result-- except IndexError as error:- warnings.warn(- "Error in file %s, " % (self.filename)- + "At time t=%.02f-%.02f seconds, " % (tt[0], tt[-1])- + "indices wanted: %d-%d, " % (indices.min(), indices.max())- + "but len(buffer)=%d\n" % (len(self.buffer))- + str(error),- UserWarning,- )-- # repeat the last frame instead- indices[indices >= len(self.buffer)] = len(self.buffer) - 1- result[in_time] = self.buffer[indices]- return result+ def get_frame(self, tt):+ """Retrieves the audio frame(s) corresponding to the given timestamp(s).- else:- ind = int(self.fps * tt)- if ind < 0 or ind > self.n_frames: # out of time: return 0- return np.zeros(self.nchannels)+ Parameters+ -----------++ tt (float or numpy.ndarray): The timestamp(s) at which to retrieve the audio frame(s).+ If `tt` is a single float value, the frame corresponding to that timestamp is returned.+ If `tt` is a NumPy array of timestamps, an array of frames corresponding to each timestamp is returned.+ """+ if isinstance(tt, np.ndarray):+ # lazy implementation, but should not cause problems in+ # 99.99 % of the cases++ # elements of t that are actually in the range of the+ # audio file.+ in_time = (tt >= 0) & (tt < self.duration)++ # Check that the requested time is in the valid range+ if not in_time.any():+ raise IOError(+ "Error in file %s, " % (self.filename)+ + "Accessing time t=%.02f-%.02f seconds, " % (tt[0], tt[-1])+ + "with clip duration=%f seconds, " % self.duration+ )++ # The np.round in the next line is super-important.+ # Removing it results in artifacts in the noise.+ frames = np.round((self.fps * tt)).astype(int)[in_time]+ fr_min, fr_max = frames.min(), frames.max()++ if not (0 <= (fr_min - self.buffer_startframe) < len(self.buffer)):+ self.buffer_around(fr_min)+ elif not (0 <= (fr_max - self.buffer_startframe) < len(self.buffer)):+ self.buffer_around(fr_max)++ try:+ result = np.zeros((len(tt), self.nchannels))+ indices = frames - self.buffer_startframe+ result[in_time] = self.buffer[indices]+ return result++ except IndexError as error:+ warnings.warn(+ "Error in file %s, " % (self.filename)+ + "At time t=%.02f-%.02f seconds, " % (tt[0], tt[-1])+ + "indices wanted: %d-%d, " % (indices.min(), indices.max())+ + "but len(buffer)=%d\n" % (len(self.buffer))+ + str(error),+ UserWarning,+ )++ # repeat the last frame instead+ indices[indices >= len(self.buffer)] = len(self.buffer) - 1+ result[in_time] = self.buffer[indices]+ return result++ else:+ ind = int(self.fps * tt)+ if ind < 0 or ind > self.n_frames: # out of time: return 0+ return np.zeros(self.nchannels)- if not (0 <= (ind - self.buffer_startframe) < len(self.buffer)):- # out of the buffer: recenter the buffer- self.buffer_around(ind)+ if not (0 <= (ind - self.buffer_startframe) < len(self.buffer)):+ # out of the buffer: recenter the buffer+ self.buffer_around(ind)- # read the frame in the buffer- return self.buffer[ind - self.buffer_startframe]+ # read the frame in the buffer+ return self.buffer[ind - self.buffer_startframe]def buffer_around(self, frame_number):"""diff --git a/moviepy/editor.py b/moviepy/editor.pyindex adf0547a..ac0b8a86 100644--- a/moviepy/editor.py+++ b/moviepy/editor.py@@ -4,8 +4,6 @@ for live editing by simply typing:>>> from moviepy.editor import *-- Starts a pygame session to enable ``clip.show()`` and ``clip.preview()``- if pygame is installed- Enables ``clip.ipython_display()`` if in an IPython Notebook- Allows the use of ``sliders`` if Matplotlib is installed"""@@ -32,13 +30,6 @@ VideoClip.ipython_display = ipython_displayAudioClip.ipython_display = ipython_display-# ------------------------------------------------------------------# Previews: try to import pygame, else make methods which raise-# exceptions saying to install PyGame--# Hide the welcome message from pygame: https://github.com/pygame/pygame/issues/542-os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"-# Add methods preview and show (only if pygame installed)try:from moviepy.video.io.preview import show, previewdiff --git a/moviepy/video/fx/painting.py b/moviepy/video/fx/painting.pyindex 4828c7dd..92fd2904 100644--- a/moviepy/video/fx/painting.py+++ b/moviepy/video/fx/painting.py@@ -1,24 +1,41 @@import numpy as np+from PIL import Image, ImageFilter+def to_painting(np_image, saturation=1.4, black=0.006):+ """Transforms any photo into some kind of painting.-# ------- CHECKING DEPENDENCIES ------------------------------------------painting_possible = True-try:- from skimage.filter import sobel-except Exception:- try:- from scipy.ndimage.filters import sobel- except Exception:- painting_possible = False-# -----------------------------------------------------------------------+ Transforms any photo into some kind of painting. Saturation+ tells at which point the colors of the result should be+ flashy. ``black`` gives the amount of black lines wanted.++ np_image : a numpy image+ """+ image = Image.fromarray(np_image)+ image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)-def to_painting(image, saturation=1.4, black=0.006):- """Transforms any photo into some kind of painting."""- edges = sobel(image.mean(axis=2))+ # Convert the image to grayscale+ grayscale_image = image.convert("L")++ # Find the image edges+ edges_image = grayscale_image.filter(ImageFilter.FIND_EDGES)++ # Convert the edges image to a numpy array+ edges = np.array(edges_image)++ # Create the darkening effectdarkening = black * (255 * np.dstack(3 * [edges]))- painting = saturation * image - darkening- return np.maximum(0, np.minimum(255, painting)).astype("uint8")++ # Apply the painting effect+ painting = saturation * np.array(image) - darkening++ # Clip the pixel values to the valid range of 0-255+ painting = np.maximum(0, np.minimum(255, painting))++ # Convert the pixel values to unsigned 8-bit integers+ painting = painting.astype("uint8")++ return paintingdef painting(clip, saturation=1.4, black=0.006):@@ -26,23 +43,6 @@ def painting(clip, saturation=1.4, black=0.006):Transforms any photo into some kind of painting. Saturationtells at which point the colors of the result should beflashy. ``black`` gives the amount of black lines wanted.- Requires Scikit-image or Scipy installed."""return clip.image_transform(lambda im: to_painting(im, saturation, black))--# ------- OVERWRITE IF REQUIREMENTS NOT MET -------------------------------if not painting_possible:- doc = painting.__doc__-- def painting(clip, saturation=None, black=None):- """Fallback painting FX function, used if scikit-image and scipy are not- installed.-- This docstring will be replaced at runtime.- """- raise IOError("fx painting needs scikit-image or scipy")-- painting.__doc__ = doc-# -----------------------------------------------------------------------diff --git a/moviepy/video/fx/resize.py b/moviepy/video/fx/resize.pyindex 7afd6189..25dcc091 100644--- a/moviepy/video/fx/resize.py+++ b/moviepy/video/fx/resize.py@@ -1,122 +1,15 @@import numbers+from PIL import Image+import numpy as np-def _get_cv2_resizer():- try:- import cv2- except ImportError:- return (None, ["OpenCV not found (install 'opencv-python')"])-- def resizer(pic, new_size):- lx, ly = int(new_size[0]), int(new_size[1])- if lx > pic.shape[1] or ly > pic.shape[0]:- # For upsizing use linear for good quality & decent speed- interpolation = cv2.INTER_LINEAR- else:- # For dowsizing use area to prevent aliasing- interpolation = cv2.INTER_AREA- return cv2.resize(+pic.astype("uint8"), (lx, ly), interpolation=interpolation)-- return (resizer, [])---def _get_PIL_resizer():- try:- from PIL import Image- except ImportError:- return (None, ["PIL not found (install 'Pillow')"])-- import numpy as np-- def resizer(pic, new_size):+def resizer(pic, new_size):new_size = list(map(int, new_size))[::-1]- # shape = pic.shape- # if len(shape) == 3:- # newshape = (new_size[0], new_size[1], shape[2])- # else:- # newshape = (new_size[0], new_size[1])pil_img = Image.fromarray(pic)resized_pil = pil_img.resize(new_size[::-1], Image.LANCZOS)- # arr = np.fromstring(resized_pil.tostring(), dtype="uint8")- # arr.reshape(newshape)return np.array(resized_pil)- return (resizer, [])---def _get_scipy_resizer():- try:- from scipy.misc import imresize- except ImportError:- try:- from scipy import __version__ as __scipy_version__- except ImportError:- return (None, ["Scipy not found (install 'scipy' or 'Pillow')"])-- scipy_version_info = tuple(- int(num) for num in __scipy_version__.split(".") if num.isdigit()- )-- # ``scipy.misc.imresize`` was removed in v1.3.0- if scipy_version_info >= (1, 3, 0):- return (- None,- [- "scipy.misc.imresize not found (was removed in scipy v1.3.0,"- f" you are using v{__scipy_version__}, install 'Pillow')"- ],- )-- # unknown reason- return (None, "scipy.misc.imresize not found")-- def resizer(pic, new_size):- return imresize(pic, map(int, new_size[::-1]))-- return (resizer, [])---def _get_resizer():- """Tries to define a ``resizer`` function using next libraries, in the given- order:-- - cv2- - PIL- - scipy-- Returns a dictionary with following attributes:-- - ``resizer``: Function used to resize images in ``resize`` FX function.- - ``origin``: Library used to resize.- - ``error_msgs``: If any of the libraries is available, shows the user why- this feature is not available and how to fix it in several error messages- which are formatted in the error displayed, if resizing is not possible.- """- error_messages = []-- resizer_getters = {- "cv2": _get_cv2_resizer,- "PIL": _get_PIL_resizer,- "scipy": _get_scipy_resizer,- }- for origin, resizer_getter in resizer_getters.items():- resizer, _error_messages = resizer_getter()- if resizer is not None:- return {"resizer": resizer, "origin": origin, "error_msgs": []}- else:- error_messages.extend(_error_messages)-- return {"resizer": None, "origin": None, "error_msgs": reversed(error_messages)}---resizer = None-_resizer_data = _get_resizer()-if _resizer_data["resizer"] is not None:- resizer = _resizer_data["resizer"]- resizer.origin = _resizer_data["origin"]- del _resizer_data["error_msgs"]-def resize(clip, new_size=None, height=None, width=None, apply_to_mask=True):"""Returns a video clip that is a resized version of the clip.@@ -215,7 +108,6 @@ def resize(clip, new_size=None, height=None, width=None, apply_to_mask=True):raise ValueError("You must provide either 'new_size' or 'height' or 'width'")# From here, the resizing is constant (not a function of time), size=newsize-if clip.is_mask:def image_filter(pic):@@ -232,21 +124,3 @@ def resize(clip, new_size=None, height=None, width=None, apply_to_mask=True):new_clip.mask = resize(clip.mask, new_size, apply_to_mask=False)return new_clip---if resizer is None:- del resizer-- doc = resize.__doc__-- def resize(clip, new_size=None, height=None, width=None):- """Fallback resize FX function, if OpenCV, Scipy and PIL are not installed.-- This docstring will be replaced at runtime.- """- fix_tips = "- " + "\n- ".join(_resizer_data["error_msgs"])- raise ImportError(f"fx resize needs OpenCV or Scipy or PIL\n{fix_tips}")-- resize.__doc__ = doc--del _resizer_data["origin"], _resizer_data["resizer"]diff --git a/moviepy/video/tools/segmenting.py b/moviepy/video/tools/segmenting.pydeleted file mode 100644index 5d281a29..00000000--- a/moviepy/video/tools/segmenting.py+++ /dev/null@@ -1,81 +0,0 @@-"""Utilities related with segmenting useful working with video clips."""--import numpy as np-import scipy.ndimage as ndi--from moviepy.video.VideoClip import ImageClip---def find_objects(clip, size_threshold=500, preview=False):- """Returns a list of ImageClips representing each a separate object on- the screen.-- Parameters- ------------ clip : video.VideoClip.ImageClip- MoviePy video clip where the objects will be searched.-- size_threshold : float, optional- Minimum size of what is considered an object. All objects found with- ``size < size_threshold`` will be considered false positives and will- be removed.-- preview : bool, optional- Previews with matplotlib the different objects found in the image before- applying the size threshold. Requires matplotlib installed.--- Examples- ---------- >>> clip = ImageClip("media/afterimage.png")- >>> objects = find_objects(clip)- >>>- >>> print(len(objects))- >>> print([obj_.screenpos for obj_ in objects])- """- image = clip.get_frame(0)- if not clip.mask: # pragma: no cover- clip = clip.with_add_mask()-- mask = clip.mask.get_frame(0)- labelled, num_features = ndi.measurements.label(image[:, :, 0])-- # find the objects- slices = []- for obj in ndi.find_objects(labelled):- if mask[obj[0], obj[1]].mean() <= 0.2:- # remove letter holes (in o,e,a, etc.)- continue- if image[obj[0], obj[1]].size <= size_threshold:- # remove very small slices- continue- slices.append(obj)- indexed_slices = sorted(enumerate(slices), key=lambda slice: slice[1][1].start)-- letters = []- for i, (sy, sx) in indexed_slices:- # crop each letter separately- sy = slice(sy.start - 1, sy.stop + 1)- sx = slice(sx.start - 1, sx.stop + 1)- letter = image[sy, sx]- labletter = labelled[sy, sx]- maskletter = (labletter == (i + 1)) * mask[sy, sx]- letter = ImageClip(image[sy, sx])- letter.mask = ImageClip(maskletter, is_mask=True)- letter.screenpos = np.array((sx.start, sy.start))- letters.append(letter)-- if preview: # pragma: no cover- import matplotlib.pyplot as plt-- print(f"Found {num_features} objects")- fig, ax = plt.subplots(2)- ax[0].axis("off")- ax[0].imshow(labelled)- ax[1].imshow([range(num_features)], interpolation="nearest")- ax[1].set_yticks([])- plt.show()-- return lettersdiff --git a/moviepy/video/tools/tracking.py b/moviepy/video/tools/tracking.pydeleted file mode 100644index ab0df233..00000000--- a/moviepy/video/tools/tracking.py+++ /dev/null@@ -1,231 +0,0 @@-"""-Contains different functions for tracking objects in videos, manually or automatically.-The tracking functions return results under the form: ``( txy, (fx,fy) )`` where txy-is of the form [(ti, xi, yi)...] and (fx(t),fy(t)) give the position of the track for-all times t (if the time t is out of the time bounds of the tracking time interval fx-and fy return the position of the object at the start or at the end of the tracking time-interval).-"""--import numpy as np--from moviepy.decorators import convert_parameter_to_seconds, use_clip_fps_by_default-from moviepy.video.io.preview import imdisplay-from moviepy.video.tools.interpolators import Trajectory---try:- import cv2-- autotracking_possible = True-except Exception:- # Note: this will be later fixed with scipy/skimage replacements- # but for the moment OpenCV is mandatory, so...- autotracking_possible = False---@convert_parameter_to_seconds(["t1", "t2"])-@use_clip_fps_by_default-def manual_tracking(clip, t1=None, t2=None, fps=None, n_objects=1, savefile=None):- """Manual tracking of objects in videoclips using the mouse.-- Allows manual tracking of an object(s) in the video clip between- times `t1` and `t2`. This displays the clip frame by frame- and you must click on the object(s) in each frame. If ``t2=None``- only the frame at ``t1`` is taken into account.-- Returns a list ``[(t1, x1, y1), (t2, x2, y2)...]`` if there is one- object per frame, else returns a list whose elements are of the- form ``(ti, [(xi1, yi1), (xi2, yi2)...])``.--- Parameters- ------------ clip : video.VideoClip.VideoClip- MoviePy video clip to track.-- t1 : float or str or tuple, optional- Start time to to track (defaults is start of the clip). Can be expressed- in seconds like ``15.35``, in ``(min, sec)``, in ``(hour, min, sec)``,- or as a string: ``"01:03:05.35"``.-- t2 : float or str or tuple, optional- End time to to track (defaults is end of the clip). Can be expressed- in seconds like ``15.35``, in ``(min, sec)``, in ``(hour, min, sec)``,- or as a string: ``"01:03:05.35"``.-- fps : int, optional- Number of frames per second to freeze on. If None, the clip's- fps attribute is used instead.-- n_objects : int, optional- Number of objects to click on each frame.-- savefile : str, optional- If provided, the result is saved to a file, which makes it easier to edit- and re-use later.--- Examples- ---------- >>> from moviepy import VideoFileClip- >>> from moviepy.video.tools.tracking import manual_tracking- >>>- >>> clip = VideoFileClip("media/chaplin.mp4")- >>>- >>> # manually indicate 3 trajectories, save them to a file- >>> trajectories = manual_tracking(clip, start_time=5, t2=7, fps=5,- ... nobjects=3, savefile="track.text")- >>>- >>> # ...- >>> # later, in another script, recover these trajectories- >>> from moviepy.video.tools.tracking import Trajectory- >>>- >>> traj1, traj2, traj3 = Trajectory.load_list('track.text')- >>>- >>> # If ever you only have one object being tracked, recover it with- >>> traj, = Trajectory.load_list('track.text')- """- import pygame as pg-- screen = pg.display.set_mode(clip.size)- step = 1.0 / fps- if (t1 is None) and (t2 is None):- t1, t2 = 0, clip.duration- elif t2 is None:- t2 = t1 + step / 2- t = t1- txy_list = []-- def gatherClicks(t):- imdisplay(clip.get_frame(t), screen)- objects_to_click = n_objects- clicks = []- while objects_to_click:- for event in pg.event.get():- if event.type == pg.KEYDOWN:- if event.key == pg.K_BACKSLASH:- return "return"- elif event.key == pg.K_ESCAPE:- raise KeyboardInterrupt()-- elif event.type == pg.MOUSEBUTTONDOWN:- x, y = pg.mouse.get_pos()- clicks.append((x, y))- objects_to_click -= 1-- return clicks-- while t < t2:- clicks = gatherClicks(t)- if clicks == "return":- txy_list.pop()- t -= step- else:- txy_list.append((t, clicks))- t += step-- tt, xylist = zip(*txy_list)- result = []- for i in range(n_objects):- xys = [e[i] for e in xylist]- xx, yy = zip(*xys)- result.append(Trajectory(tt, xx, yy))-- if savefile is not None:- Trajectory.save_list(result, savefile)- return result---def findAround(pic, pat, xy=None, r=None):- """Find an image pattern in a picture optionally defining bounds to search.-- The image is found is ``pat`` is inside ``pic[x +/- r, y +/- r]``.-- Parameters- ------------ pic : numpy.ndarray- Image where the pattern will be searched.-- pat : numpy.ndarray- Pattern to search inside the image.-- xy : tuple or list, optional- Position to search for the pattern. Use it in combination with ``radius``- parameter to define the bounds of the search. If is ``None``, consider- the whole picture.-- r : float, optional- Radius used to define the bounds of the search when ``xy`` argument is- defined.- """- if xy and r:- h, w = pat.shape[:2]- x, y = xy- pic = pic[y - r : y + h + r, x - r : x + w + r]-- matches = cv2.matchTemplate(pat, pic, cv2.TM_CCOEFF_NORMED)- yf, xf = np.unravel_index(matches.argmax(), matches.shape)- return (x - r + xf, y - r + yf) if (xy and r) else (xf, yf)---def autoTrack(clip, pattern, tt=None, fps=None, radius=20, xy0=None):- """Tracks a given pattern (small image array) in a video clip.-- Returns ``[(x1, y1), (x2, y2)...]`` where ``(xi, yi)`` are the coordinates- of the pattern in the clip on frame ``i``. To select the frames you can- either specify a list of times with ``tt`` or select a frame rate with- ``fps``.-- This algorithm assumes that the pattern's aspect does not vary much and- that the distance between two occurrences of the pattern in two consecutive- frames is smaller than ``radius`` (if you set ``radius`` to -1 the pattern- will be searched in the whole screen at each frame). You can also provide- the original position of the pattern with xy0.-- Parameters- ------------ clip : video.VideoClip.VideoClip- MoviePy video clip to track.-- pattern : numpy.ndarray- Image to search inside the clip frames.-- tt : numpy.ndarray, optional- Time frames used for auto tracking. As default is used the clip time- frames according to its fps.-- fps : int, optional- Overwrites fps value used computing time frames. As default, clip's fps.-- radius : int, optional- Maximum radius to search looking for the pattern. Set to ``-1``,- the pattern will be searched in the whole screen at each frame.-- xy0 : tuple or list, optional- Original position of the pattern. If not provided, will be taken from the- first tracked frame of the clip.- """- if not autotracking_possible:- raise IOError(- "Sorry, autotrack requires OpenCV for the moment. "- "Install OpenCV (aka cv2) to use it."- )-- if not xy0:- xy0 = findAround(clip.get_frame(tt[0]), pattern)-- if tt is None:- tt = np.arange(0, clip.duration, 1.0 / fps)-- xys = [xy0]- for t in tt[1:]:- xys.append(findAround(clip.get_frame(t), pattern, xy=xys[-1], r=radius))-- xx, yy = zip(*xys)-- return Trajectory(tt, xx, yy)