Skip to content

Video editing with Python

Fix some performances regressions introduced in v2 and v2.1.2 with support for transparency

osaajani55d5486aab82
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index 280af56c..1b042d85 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -775,9 +775,17 @@ class VideoClip(Clip):
background.paste(clip_img, pos)
return background
+ # If background has no alpha layer, we can just paste img on top of it
+ # this is far more efficient than alpha compositing
+ if background.mode[-1] != "A":
+ background.paste(clip_img, pos, mask=clip_img)
+ return background
+
# For images with transparency we must use pillow alpha composite
# instead of a simple paste, because pillow paste dont work nicely
# with alpha compositing
+ # Only do this in last resort, as it is slower than a simple paste
+ # and we dont want to use it if we dont have to
if background.mode[-1] != "A":
background = background.convert("RGBA")
@@ -788,7 +796,10 @@ class VideoClip(Clip):
# so we must start by making a fully transparent canvas of background's
# size and paste our clip img into it in position pos, only then can we
# composite this canvas on top of background
- canvas = Image.new("RGBA", (background.width, background.height), (0, 0, 0, 0))
+ # Its actually faster to make the canvas in numpy and then convert it to PIL
+ # than to make it in PIL directly
+ canvas_np = np.zeros((background.height, background.width, 4), dtype=np.uint8)
+ canvas = Image.fromarray(canvas_np)
canvas.paste(clip_img, pos)
result = Image.alpha_composite(background, canvas)
return result
@@ -1310,6 +1321,11 @@ class ImageClip(VideoClip):
Set this parameter to `True` (default) if you want the alpha layer
of the picture (if it exists) to be used as a mask.
+ duration
+ Duration of the clip in seconds. If not provided, the clip will
+ have infinite duration (i.e. it will be displayed until the end of the
+ composition in which it is included).
+
Attributes
----------
@@ -1318,9 +1334,7 @@ class ImageClip(VideoClip):
"""
- def __init__(
- self, img, is_mask=False, transparent=True, fromalpha=False, duration=None
- ):
+ def __init__(self, img, is_mask=False, transparent=True, duration=None):
VideoClip.__init__(self, is_mask=is_mask, duration=duration)
if not isinstance(img, np.ndarray):
@@ -1329,9 +1343,7 @@ class ImageClip(VideoClip):
if len(img.shape) == 3: # img is (now) a RGB(a) numpy array
if img.shape[2] == 4:
- if fromalpha:
- img = 1.0 * img[:, :, 3] / 255
- elif is_mask:
+ if is_mask:
img = 1.0 * img[:, :, 0] / 255
elif transparent:
self.mask = ImageClip(1.0 * img[:, :, 3] / 255, is_mask=True)
diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.py
index ba6a8cd4..ef753ef4 100644
--- a/moviepy/video/compositing/CompositeVideoClip.py
+++ b/moviepy/video/compositing/CompositeVideoClip.py
@@ -42,6 +42,7 @@ class CompositeVideoClip(VideoClip):
bg_color
Color for the unmasked and unfilled regions. Set to None for these
regions to be transparent (will be slower).
+ Default is black (0, 0, 0).
use_bgclip
Set to True if the first clip in the list should be used as the
@@ -54,7 +55,7 @@ class CompositeVideoClip(VideoClip):
"""
def __init__(
- self, clips, size=None, bg_color=None, use_bgclip=False, is_mask=False
+ self, clips, size=None, bg_color=(0, 0, 0), use_bgclip=False, is_mask=False
):
if size is None:
size = clips[0].size
@@ -169,12 +170,22 @@ class CompositeVideoClip(VideoClip):
current_img = clip.compose_on(current_img, t)
# Turn Pillow image into a numpy array
- frame = np.array(current_img)
+ # force contigous for perfs
+ frame = np.ascontiguousarray(current_img)
# If frame have transparency, remove it
# our mask will take care of it during rendering
if frame.shape[2] == 4:
- return frame[:, :, :3]
+ # Manual copy is more performent than np copy
+ # and ensure C order for later rendering
+ h, w = frame.shape[:2]
+ rgb = np.empty((h, w, 3), dtype=frame.dtype, order="C")
+ rgb[..., 0] = frame[..., 0]
+ rgb[..., 1] = frame[..., 1]
+ rgb[..., 2] = frame[..., 2]
+
+ del frame
+ return rgb
return frame
diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.py
index 73ff0a54..71c301cd 100644
--- a/moviepy/video/io/ffmpeg_writer.py
+++ b/moviepy/video/io/ffmpeg_writer.py
@@ -181,7 +181,12 @@ class FFMPEG_VideoWriter:
def write_frame(self, img_array):
"""Writes one frame in the file."""
try:
- self.proc.stdin.write(img_array.tobytes())
+ # ffmpeg expects the data to be in C order, so we ensure that
+ # the input array is contiguous in memory.
+ if not img_array.flags["C_CONTIGUOUS"]:
+ img_array = img_array.copy(order="C")
+
+ self.proc.stdin.write(img_array)
except IOError as err:
_, ffmpeg_error = self.proc.communicate()
if ffmpeg_error is not None:
diff --git a/tests/test_compositing.py b/tests/test_compositing.py
index 6937007b..3ba11391 100644
--- a/tests/test_compositing.py
+++ b/tests/test_compositing.py
@@ -117,10 +117,12 @@ def test_compositing_masks(util):
clip3 = ColorClip((25, 25), (0, 0, 255, 76.5)).with_duration(2)
compostite_clip1 = CompositeVideoClip(
- [clip1, clip2.with_position(("center", "center"))]
+ [clip1, clip2.with_position(("center", "center"))],
+ bg_color=None,
)
compostite_clip2 = CompositeVideoClip(
- [compostite_clip1, clip3.with_position(("center", "center"))]
+ [compostite_clip1, clip3.with_position(("center", "center"))],
+ bg_color=None,
)
# Load output file and check transparency
@@ -144,10 +146,12 @@ def test_compositing_with_transparency_colors(util):
clip3 = ColorClip((25, 25), (0, 0, 255, 76.5)).with_duration(2)
compostite_clip1 = CompositeVideoClip(
- [clip1, clip2.with_position(("center", "center"))]
+ [clip1, clip2.with_position(("center", "center"))],
+ bg_color=None, # No background color, so it should be transparent
)
compostite_clip2 = CompositeVideoClip(
- [compostite_clip1, clip3.with_position(("center", "center"))]
+ [compostite_clip1, clip3.with_position(("center", "center"))],
+ bg_color=None,
)
# Load output file and check transparency
diff --git a/tests/test_issues.py b/tests/test_issues.py
index 79a086df..ba5d5b56 100644
--- a/tests/test_issues.py
+++ b/tests/test_issues.py
@@ -374,9 +374,13 @@ def test_issue_2269(util):
).with_duration(3)
comp1 = CompositeVideoClip(
- [color_clip, txt_clip_with_margin.with_position(("center", "center"))]
+ [color_clip, txt_clip_with_margin.with_position(("center", "center"))],
+ bg_color=None, # No background color, so it should be transparent
+ )
+ comp2 = CompositeVideoClip(
+ [clip, comp1.with_position(("center", "center"))],
+ bg_color=None, # No background color, so it should be transparent
)
- comp2 = CompositeVideoClip([clip, comp1.with_position(("center", "center"))])
# If transparency work as expected, this pixel should be pure red at 2 seconds
frame = comp2.get_frame(2)
@@ -393,10 +397,12 @@ def test_issue_2269_2(util):
clip3 = ColorClip((50, 50), (0, 0, 255, 76.5)).with_duration(3)
compostite_clip1 = CompositeVideoClip(
- [clip1, clip2.with_position(("center", "center"))]
+ [clip1, clip2.with_position(("center", "center"))],
+ bg_color=None,
)
compostite_clip2 = CompositeVideoClip(
- [compostite_clip1, clip3.with_position(("center", "center"))]
+ [compostite_clip1, clip3.with_position(("center", "center"))],
+ bg_color=None,
)
# If transparency work as expected the clip should match thoses colors
@@ -419,10 +425,12 @@ def test_issue_2269_3(util):
clip3 = ColorClip((50, 50), (0, 0, 255, 76.5)).with_duration(3)
compostite_clip1 = CompositeVideoClip(
- [clip1, clip2.with_position(("center", "center"))]
+ [clip1, clip2.with_position(("center", "center"))],
+ bg_color=None,
)
compostite_clip2 = CompositeVideoClip(
- [compostite_clip1, clip3.with_position(("center", "center"))]
+ [compostite_clip1, clip3.with_position(("center", "center"))],
+ bg_color=None,
)
# If transparency work as expected the clip transparency should be between 0.3 and 0.657