Skip to content

Video editing with Python

Re-introduce opencv for image rotation and resize, increasing perfs

osaajani1f48b05828b3
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index b17bb4d9..9a4d3e0c 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -1551,9 +1551,9 @@ class ColorClip(ImageClip):
)
shape = (h, w, len(color))
- super().__init__(
- np.tile(color, w * h).reshape(shape), is_mask=is_mask, duration=duration
- )
+ arr = np.tile(color, w * h).reshape(shape)
+ arr = arr.astype(np.float32) if is_mask else arr.astype(np.uint8)
+ super().__init__(arr, is_mask=is_mask, duration=duration)
class TextClip(ImageClip):
@@ -2196,7 +2196,7 @@ class BitmapClip(VideoClip):
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_list.append(np.array(output_frame, dtype=np.uint8))
frame_array = np.array(frame_list)
self.total_frames = len(frame_array)
diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.py
index 64e8dc93..1131ecdc 100644
--- a/moviepy/video/compositing/CompositeVideoClip.py
+++ b/moviepy/video/compositing/CompositeVideoClip.py
@@ -158,7 +158,11 @@ class CompositeVideoClip(VideoClip):
# For the mask we recalculate the final transparency we'll need
# to apply on the result image
if self.is_mask:
- if self.memoize_mask and t in self.precomputed:
+ if (
+ self.memoize_mask
+ and t in self.precomputed
+ and self.precomputed[t] is not None
+ ):
mask = self.precomputed[t].copy()
del self.precomputed[t] # Free memory as soon as possible
return mask
@@ -169,7 +173,7 @@ class CompositeVideoClip(VideoClip):
return mask
- # Try doing clip merging without pillow
+ # Clip merging in pure numpy
bg_t = t - self.bg.start
bg_frame = self.bg.get_frame(bg_t).astype("uint8")
clip_height, clip_width = bg_frame.shape[:2]
diff --git a/moviepy/video/fx/HeadBlur.py b/moviepy/video/fx/HeadBlur.py
index 83aec1a7..0651fa1e 100644
--- a/moviepy/video/fx/HeadBlur.py
+++ b/moviepy/video/fx/HeadBlur.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass
+import cv2
import numpy as np
-from PIL import Image, ImageDraw, ImageFilter
from moviepy.Clip import Clip
from moviepy.Effect import Effect
@@ -25,21 +25,28 @@ class HeadBlur(Effect):
if self.intensity is None:
self.intensity = int(2 * self.radius / 3)
- def filter(gf, t):
- im = gf(t).copy()
+ def filter(get_frame, t):
+ im = get_frame(t).copy()
h, w, d = im.shape
x, y = int(self.fx(t)), int(self.fy(t))
- x1, x2 = max(0, x - self.radius), min(x + self.radius, w)
- y1, y2 = max(0, y - self.radius), min(y + self.radius, h)
-
- image = Image.fromarray(im)
- mask = Image.new("RGB", image.size)
- draw = ImageDraw.Draw(mask)
- draw.ellipse([x1, y1, x2, y2], fill=(255, 255, 255))
-
- blurred = image.filter(ImageFilter.GaussianBlur(radius=self.intensity))
-
- res = np.where(np.array(mask) > 0, np.array(blurred), np.array(image))
- return res
+ # Create a mask for the blur area
+ blur_mask = np.zeros((h, w), dtype=np.uint8)
+ cv2.circle(blur_mask, (x, y), int(self.radius), 255, -1)
+
+ # Blur the image, size of the kernel must be odd
+ gaussian_kernel = int(
+ self.intensity * 6
+ ) # 6 is a factor somewhat match the intensity of previous versions
+ gaussian_kernel = (
+ gaussian_kernel + 1 if gaussian_kernel % 2 == 0 else gaussian_kernel
+ )
+
+ blurred_im = cv2.GaussianBlur(
+ im, (gaussian_kernel, gaussian_kernel), sigmaX=0
+ )
+ blur_mask = cv2.cvtColor(blur_mask, cv2.COLOR_GRAY2BGR)
+
+ res = np.where(blur_mask == 255, blurred_im, im)
+ return np.array(res, dtype=np.uint8)
return clip.transform(filter)
diff --git a/moviepy/video/fx/MultiplyColor.py b/moviepy/video/fx/MultiplyColor.py
index 6a3e1b70..0d41b5fb 100644
--- a/moviepy/video/fx/MultiplyColor.py
+++ b/moviepy/video/fx/MultiplyColor.py
@@ -19,5 +19,7 @@ class MultiplyColor(Effect):
def apply(self, clip: Clip) -> Clip:
"""Apply the effect to the clip."""
return clip.image_transform(
- lambda frame: np.minimum(255, (self.factor * frame)).astype("uint8")
+ lambda frame: np.minimum(
+ 255, np.multiply(frame, self.factor, dtype=np.float32)
+ ).astype("uint8")
)
diff --git a/moviepy/video/fx/Resize.py b/moviepy/video/fx/Resize.py
index 44b857d3..1f42f469 100644
--- a/moviepy/video/fx/Resize.py
+++ b/moviepy/video/fx/Resize.py
@@ -2,8 +2,7 @@ import numbers
from dataclasses import dataclass
from typing import Union
-import numpy as np
-from PIL import Image
+import cv2
from moviepy.Effect import Effect
@@ -46,11 +45,15 @@ class Resize(Effect):
apply_to_mask: bool = True
def resizer(self, pic, new_size):
- """Resize the image using PIL."""
- new_size = list(map(int, new_size))
- pil_img = Image.fromarray(pic)
- resized_pil = pil_img.resize(new_size, Image.Resampling.LANCZOS)
- return np.array(resized_pil)
+ """Resize the image using openCV."""
+ 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)
def apply(self, clip):
"""Apply the effect to the clip."""
diff --git a/moviepy/video/fx/Rotate.py b/moviepy/video/fx/Rotate.py
index 4fb9a593..62e5e949 100644
--- a/moviepy/video/fx/Rotate.py
+++ b/moviepy/video/fx/Rotate.py
@@ -1,8 +1,9 @@
import math
from dataclasses import dataclass
+from typing import Union
+import cv2
import numpy as np
-from PIL import Image
from moviepy.Clip import Clip
from moviepy.Effect import Effect
@@ -57,13 +58,114 @@ class Rotate(Effect):
translate: tuple = None
bg_color: tuple = None
+ def rotate_frame(
+ self,
+ frame: np.ndarray,
+ angle: float,
+ resample: int,
+ expand: bool,
+ center: Union[tuple, None],
+ translate: Union[tuple, None],
+ bg_color: Union[tuple, None],
+ ) -> np.ndarray:
+ """
+ Rotate a single image or mask using OpenCV.
+
+ Parameters
+ ----------
+ frame : np.ndarray
+ HxWxC RGB image (dtype uint8) or HxW mask (any dtype).
+
+ angle : float
+ Counter-clockwise rotation angle in degrees.
+
+ resample : int
+ One of cv2.INTER_NEAREST, cv2.INTER_LINEAR, or cv2.INTER_CUBIC.
+ For masks, you’ll typically want cv2.INTER_NEAREST.
+ Default is cv2.INTER_CUBIC.
+
+ expand : bool
+ If True, expand the output canvas so the full rotated frame fits.
+ If False, output size == input size (cropping corners). Default False.
+ Expansion does not account for translation.
+
+ center : tuple or None
+ (cx, cy) rotation center in pixel coords. Defaults to image center.
+
+ translate : tuple or None
+ (dx, dy) post-rotation translation in pixels. Default (0, 0).
+
+ bg_color : tuple, scalar, or None
+ Fill color for areas outside the frame.
+ If `frame` is HxWx3 RGB, bg_color=(R,G,B).
+ If HxW mask, bg_color is a scalar. Default black.
+
+ Returns
+ -------
+ rotated : np.ndarray
+ The rotated (and possibly expanded) frame or mask.
+ """
+ h, w = frame.shape[:2]
+
+ if bg_color is None:
+ bg_color = (0, 0, 0) if len(frame.shape) == 3 else 0
+
+ # compute center
+ cx, cy = center if center is not None else (w / 2, h / 2)
+
+ # rotation matrix
+ rotation_matrix = cv2.getRotationMatrix2D((cx, cy), angle, 1)
+
+ # expand canvas
+ if expand:
+ cos = np.abs(rotation_matrix[0, 0])
+ sin = np.abs(rotation_matrix[0, 1])
+
+ # compute the new bounding dimensions of the image
+ new_w = math.ceil((h * sin) + (w * cos))
+ new_h = math.ceil((h * cos) + (w * sin))
+
+ # adjust the rotation matrix to take into account translation
+ rotation_matrix[0, 2] += int(new_w / 2) - cx
+ rotation_matrix[1, 2] += int(new_h / 2) - cy
+
+ out_size = (new_w, new_h)
+ else:
+ out_size = (w, h)
+
+ # Rotate the image
+ rotated = cv2.warpAffine(
+ frame,
+ rotation_matrix,
+ out_size,
+ flags=resample,
+ borderMode=cv2.BORDER_CONSTANT,
+ borderValue=bg_color,
+ )
+
+ # If translate is specified, apply it after rotation
+ if translate is not None:
+ translation_matrix = np.float32(
+ [[1, 0, translate[0]], [0, 1, translate[1]]]
+ )
+ rotated = cv2.warpAffine(
+ rotated,
+ translation_matrix,
+ (rotated.shape[1], rotated.shape[0]),
+ flags=resample,
+ borderMode=cv2.BORDER_CONSTANT,
+ borderValue=bg_color,
+ )
+
+ return rotated
+
def apply(self, clip: Clip) -> Clip:
"""Apply the effect to the clip."""
try:
resample = {
- "bilinear": Image.BILINEAR,
- "nearest": Image.NEAREST,
- "bicubic": Image.BICUBIC,
+ "nearest": cv2.INTER_NEAREST,
+ "bilinear": cv2.INTER_LINEAR,
+ "bicubic": cv2.INTER_CUBIC,
}[self.resample]
except KeyError:
raise ValueError(
@@ -95,34 +197,14 @@ class Rotate(Effect):
elif (angle == 180) and self.expand:
return im[::-1, ::-1]
- pillow_kwargs = {}
-
- if self.bg_color is not None:
- pillow_kwargs["fillcolor"] = self.bg_color
-
- if self.center is not None:
- pillow_kwargs["center"] = self.center
-
- if self.translate is not None:
- pillow_kwargs["translate"] = self.translate
-
- # PIL expects uint8 type data. However a mask image has values in the
- # range [0, 1] and is of float type. To handle this we scale it up by
- # a factor 'a' for use with PIL and then back again by 'a' afterwards.
- if im.dtype == "float64":
- # this is a mask image
- a = 255.0
- else:
- a = 1
-
- # call PIL.rotate
- return (
- np.array(
- Image.fromarray(np.array(a * im).astype(np.uint8)).rotate(
- angle, expand=self.expand, resample=resample, **pillow_kwargs
- )
- )
- / a
+ return self.rotate_frame(
+ im,
+ angle,
+ resample,
+ self.expand,
+ self.center,
+ self.translate,
+ self.bg_color,
)
return clip.transform(filter, apply_to=["mask"])
diff --git a/pyproject.toml b/pyproject.toml
index 65a4ef31..71fdf6c8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "moviepy"
-version = "2.1.2"
+version = "2.2.0"
description = "Video editing with Python"
readme = "README.md"
license = { text = "MIT License" }
@@ -35,6 +35,7 @@ dependencies = [
"proglog<=1.0.0",
"python-dotenv>=0.10",
"pillow>=9.2.0",
+ "opencv-python-headless>=4.0.0",
]
[project.optional-dependencies]
diff --git a/tests/test_PR.py b/tests/test_PR.py
index 0acd3f68..85bb2f3d 100644
--- a/tests/test_PR.py
+++ b/tests/test_PR.py
@@ -69,8 +69,6 @@ def test_PR_528(util):
def test_PR_529():
- # print(ffmpeg_tools.ffplay_version())
- print(ffmpeg_tools.ffmpeg_version())
with VideoFileClip("media/fire2.mp4") as video_clip:
assert video_clip.rotation == 180
diff --git a/tests/test_TextClip.py b/tests/test_TextClip.py
index 115ea70f..675d5111 100644
--- a/tests/test_TextClip.py
+++ b/tests/test_TextClip.py
@@ -114,7 +114,6 @@ def test_label_autosizing(util):
first_column, last_column = (margin_frame[:, 0], margin_frame[:, -1])
# We add a bit of tolerance (about 1%) to account for possible rounding errors
- # print(first_row, last_row, first_column, last_column)
assert np.allclose(first_row, [0, 0, 0], rtol=0.01)
assert np.allclose(last_row, [0, 0, 0], rtol=0.01)
assert np.allclose(first_column, [0, 0, 0], rtol=0.01)
diff --git a/tests/test_compositing.py b/tests/test_compositing.py
index bbefe680..52f818c3 100644
--- a/tests/test_compositing.py
+++ b/tests/test_compositing.py
@@ -163,19 +163,19 @@ def test_compositing_with_transparency_colors(util):
# For possible rounding errors
color1 = frame[50, 10]
opacity1 = mask[50, 10]
- assert np.allclose(color1, [255, 0, 0], rtol=1)
+ assert np.allclose(color1, [255, 0, 0], atol=1)
assert abs(opacity1 - 0.3) < 0.01
# With 2 layers
color2 = frame[50, 30]
opacity2 = mask[50, 30]
- assert np.allclose(color2, [105, 150, 0], rtol=1)
+ assert np.allclose(color2, [105, 150, 0], atol=1)
assert abs(opacity2 - 0.51) < 0.01
# With 3 layers
color3 = frame[50, 50]
opacity3 = mask[50, 50]
- assert np.allclose(color3, [56, 81, 116], rtol=1)
+ assert np.allclose(color3, [56, 81, 116], atol=1)
assert abs(opacity3 - 0.657) < 0.01
diff --git a/tests/test_fx.py b/tests/test_fx.py
index f7a6e75e..fb0f48b3 100644
--- a/tests/test_fx.py
+++ b/tests/test_fx.py
@@ -7,6 +7,7 @@ import os
import random
import numpy as np
+from PIL import Image, ImageDraw
import pytest
@@ -109,7 +110,7 @@ def test_multiply_color():
clipfx = clip.with_effects([vfx.MultiplyColor(4)])
target = BitmapClip([["HHO", "BHO"]], color_dict=color_dict, fps=1)
- assert target == clipfx
+ assert np.allclose(target.get_frame(0), clipfx.get_frame(0), atol=1)
def test_crop():
@@ -816,7 +817,8 @@ def test_resize(apply_to_mask, size, duration, new_size, height, width):
"translate",
"center",
"bg_color",
- "expected_frames",
+ "pixel_positions",
+ "expected_pixels",
),
(
(
@@ -824,65 +826,48 @@ def test_resize(apply_to_mask, size, duration, new_size, height, width):
None,
None,
None,
- [["AAAA", "BBBB", "CCCC"], ["ABCD", "BCDE", "CDEA"]],
+ [(10, 1)],
+ [(0, 0, 0)],
),
(
90,
None,
None,
None,
- [["ABC", "ABC", "ABC", "ABC"], ["DEA", "CDE", "BCD", "ABC"]],
+ [(50, 50)],
+ [(255, 255, 255)],
),
(
lambda t: 90,
None,
None,
None,
- [["ABC", "ABC", "ABC", "ABC"], ["DEA", "CDE", "BCD", "ABC"]],
- ),
- (
- 180,
- None,
- None,
- None,
- [["CCCC", "BBBB", "AAAA"], ["AEDC", "EDCB", "DCBA"]],
- ),
- (
- 270,
- None,
- None,
- None,
- [["CBA", "CBA", "CBA", "CBA"], ["CBA", "DCB", "EDC", "AED"]],
+ [(50, 50)],
+ [(255, 255, 255)],
),
(
45,
- (50, 50),
None,
- (0, 255, 0),
- [
- ["GGGGGG", "GGGGGG", "GGGGGG", "GGGGGG", "GGGGGG", "GGGGGG"],
- ["GGGGGG", "GGGGGG", "GGGGGG", "GGGGGG", "GGGGGG", "GGGGGG"],
- ],
+ None,
+ (255, 0, 0),
+ [(10, 10), (100, 350)],
+ [(255, 0, 0), (255, 255, 255)],
),
(
45,
(50, 50),
(20, 20),
(255, 0, 0),
- [
- ["RRRRRR", "RRRRRR", "RRRRRR", "RRRRRR", "RRRRRR"],
- ["RRRRRR", "RRRRRR", "RRRRRR", "RRRRRR", "RRRRRR"],
- ],
+ [(10, 10), (10, 560), (85, 560)],
+ [(255, 0, 0), (255, 0, 0), (255, 255, 255)],
),
(
135,
- (-100, -100),
None,
- (0, 0, 255),
- [
- ["BBBBBB", "BBBBBB", "BBBBBB", "BBBBBB", "BBBBBB"],
- ["BBBBBB", "BBBBBB", "BBBBBB", "BBBBBB", "BBBBBB"],
- ],
+ (0, 0),
+ (255, 0, 0),
+ [(10, 10), (10, 100), (100, 10)],
+ [(255, 255, 255), (0, 255, 0), (255, 0, 0)],
),
),
)
@@ -893,10 +878,28 @@ def test_rotate(
translate,
center,
bg_color,
- expected_frames,
+ pixel_positions,
+ expected_pixels,
):
"""Check ``rotate`` FX behaviour against possible combinations of arguments."""
- original_frames = [["AAAA", "BBBB", "CCCC"], ["ABCD", "BCDE", "CDEA"]]
+ img = Image.new("RGB", (500, 300), (0, 255, 0))
+ draw = ImageDraw.Draw(img)
+
+ # Draw a black triangle starting at (0, 0)
+ triangle_coords = [(0, 0), (200, 180), (0, 180)]
+ draw.polygon(triangle_coords, fill="black")
+
+ # Draw a white square with its top-right corner at (500, 0)
+ square_side = 150
+ square_coords = [(500 - square_side, 0), (500, square_side)]
+ draw.rectangle(square_coords, fill="white")
+
+ # Draw a gray circle with its bottom-right at (500, 300)
+ circle_diameter = 100
+ circle_bbox = [(500 - circle_diameter, 300 - circle_diameter), (500, 300)]
+ draw.ellipse(circle_bbox, fill="gray")
+
+ clip = ImageClip(np.array(img, dtype=np.uint8)).with_duration(1).with_fps(1)
# angles are defined in degrees, so convert to radians testing ``unit="rad"``
if unit == "rad":
@@ -906,7 +909,6 @@ def test_rotate(
_angle = math.radians(angle)
else:
_angle = angle
- clip = BitmapClip(original_frames, fps=1)
kwargs = {
"unit": unit,
@@ -933,9 +935,13 @@ def test_rotate(
_resolved_angle = math.degrees(_resolved_angle)
rotated_clip = clip.with_effects([vfx.Rotate(_angle, **kwargs)])
- expected_clip = BitmapClip(expected_frames, fps=1)
+ # rotated_clip.show(0)
- assert rotated_clip.to_bitmap() == expected_clip.to_bitmap()
+ for pixel_position, expected_pixel in zip(pixel_positions, expected_pixels):
+ pixel = rotated_clip.get_frame(0)[pixel_position[0]][pixel_position[1]]
+ print(pixel, expected_pixel)
+ # Check if the pixel at the specified position matches the expected color
+ assert (pixel == expected_pixel).all()
def test_rotate_nonstandard_angles(util):
diff --git a/tests/test_issues.py b/tests/test_issues.py
index ba5d5b56..851070a8 100644
--- a/tests/test_issues.py
+++ b/tests/test_issues.py
@@ -438,9 +438,9 @@ def test_issue_2269_3(util):
pixel1 = frame[100, 10]
pixel2 = frame[100, 60]
pixel3 = frame[100, 100]
- assert pixel1 == 0.3
- assert pixel2 == 0.51
- assert pixel3 == 0.657
+ assert pixel1 - 0.3 < 0.01
+ assert pixel2 - 0.51 < 0.01
+ assert pixel3 - 0.657 < 0.01
def test_issue_2160(util):