Skip to content

Video editing with Python

Fix multiple bugs in transparency, mainly in video compositing, still need to fix reading i think

osaajani51572906316e
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index fd43a81a..a76e0daf 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -718,6 +718,8 @@ class VideoClip(Clip):
"""Returns the result of the blit of the clip's frame at time `t`
on the given `picture`, the position of the clip being given
by the clip's ``pos`` attribute. Meant for compositing.
+
+ (note: blitting is the fact of putting an image on a surface or another image)
"""
wf, hf = picture.size
@@ -744,7 +746,6 @@ class VideoClip(Clip):
im_mask_bg.paste(im_mask, (0, 0))
im_img, im_mask = im_img_bg, im_mask_bg
-
else:
im_mask = None
@@ -780,6 +781,92 @@ class VideoClip(Clip):
pos = map(int, pos)
return blit(im_img, picture, pos, mask=im_mask)
+
+ def blit_mask(self, base_mask, t):
+ """Returns the result of the blit of the clip's mask at time `t`
+ on the given `base_mask`, the position of the clip being given
+ by the clip's ``pos`` attribute. Meant for compositing.
+
+ (warning: only use this function to blit two masks together, never images)
+
+ (note: blitting is the fact of putting an image on a surface or another image)
+ """
+ ct = t - self.start # clip time
+ clip_mask = self.get_frame(ct).astype("float")
+
+ # numpy shape is H*W not W*H
+ hbm, wbm = base_mask.shape
+ hcm, wcm = clip_mask.shape
+
+ # SET POSITION
+ pos = self.pos(ct)
+
+ # preprocess short writings of the position
+ if isinstance(pos, str):
+ pos = {
+ "center": ["center", "center"],
+ "left": ["left", "center"],
+ "right": ["right", "center"],
+ "top": ["center", "top"],
+ "bottom": ["center", "bottom"],
+ }[pos]
+ else:
+ pos = list(pos)
+
+ # is the position relative (given in % of the clip's size) ?
+ if self.relative_pos:
+ for i, dim in enumerate([wbm, hbm]):
+ if not isinstance(pos[i], str):
+ pos[i] = dim * pos[i]
+
+ if isinstance(pos[0], str):
+ D = {"left": 0, "center": (wbm - wcm) / 2, "right": wbm - wcm}
+ pos[0] = int(D[pos[0]])
+
+ if isinstance(pos[1], str):
+ D = {"top": 0, "center": (hbm - hcm) / 2, "bottom": hbm - hcm}
+ pos[1] = int(D[pos[1]])
+
+ # ALPHA COMPOSITING
+ # Determine the base_mask region to merge size
+ x_start = max(pos[0], 0) # Dont go under 0 left
+ x_end = min(pos[0] + wcm, wbm) # Dont go over base_mask width
+ y_start = max(pos[1], 0) # Dont go under 0 top
+ y_end = min(pos[1] + hcm, hbm) # Dont go over base_mask height
+
+ # Determine the clip_mask region to overlapp
+ # Dont go under 0 for horizontal, if we have negative margin of X px start at X
+ # And dont go over clip width
+ clip_x_start = max(0, -pos[0])
+ clip_x_end = clip_x_start + min((x_end - x_start), (wcm - clip_x_start))
+ # same for vertical
+ clip_y_start = max(0, -pos[1])
+ clip_y_end = clip_y_start + min((y_end - y_start), (hcm - clip_y_start))
+
+ # Blend the overlapping regions
+ # The calculus is base_opacity + clip_opacity * (1 - base_opacity)
+ # this ensure that masks are drawn in the right order and
+ # the contribution of each mask is proportional to their transparency
+ #
+ # Note :
+ # Thinking in transparency is hard, as we tend to think
+ # that 50% opaque + 40% opaque = 90% opacity, when it really its 70%
+ # It's a lot easier to think in terms of "passing light"
+ # Consider I emit 100 photons, and my first layer is 50% opaque, meaning it
+ # will "stop" 50% of the photons, I'll have 50 photons left
+ # now my second layer is blocking 40% of thoses 50 photons left
+ # blocking 50 * 0.4 = 20 photons, and leaving me with only 30 photons
+ # So, by adding two layer of 50% and 40% opacity my finaly opacity is only
+ # of (100-30)*100 = 70% opacity !
+ base_mask[y_start:y_end, x_start:x_end] = (
+ base_mask[y_start:y_end, x_start:x_end] +
+ clip_mask[clip_y_start:clip_y_end, clip_x_start:clip_x_end] *
+ (1 - base_mask[y_start:y_end, x_start:x_end])
+ )
+
+ return base_mask
+
+
def with_background_color(self, size=None, color=(0, 0, 0), pos=None, opacity=None):
"""Place the clip on a colored background.
diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.py
index 28b32b1f..3a296415 100644
--- a/moviepy/video/compositing/CompositeVideoClip.py
+++ b/moviepy/video/compositing/CompositeVideoClip.py
@@ -67,6 +67,8 @@ class CompositeVideoClip(VideoClip):
if bg_color is None:
bg_color = 0.0 if is_mask else (0, 0, 0)
+ print(clips)
+
fpss = [clip.fps for clip in clips if getattr(clip, "fps", None)]
self.fps = max(fpss) if fpss else None
@@ -121,6 +123,14 @@ class CompositeVideoClip(VideoClip):
frame = self.bg.get_frame(t).astype("uint8")
im = Image.fromarray(frame)
+ # For the mask we dont blit on each other, instead we recalculate the final transparency of the masks
+ if self.is_mask :
+ mask = np.zeros((self.size[1], self.size[0]), dtype=float)
+ for clip in self.playing_clips(t):
+ mask = clip.blit_mask(mask, t)
+
+ return mask
+
if self.bg.mask is not None:
frame_mask = self.bg.mask.get_frame(t)
im_mask = Image.fromarray(255 * frame_mask).convert("L")
diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.py
index cbae415a..632e6edc 100644
--- a/moviepy/video/io/ffmpeg_writer.py
+++ b/moviepy/video/io/ffmpeg_writer.py
@@ -95,8 +95,8 @@ class FFMPEG_VideoWriter:
self.filename = filename
self.codec = codec
self.ext = self.filename.split(".")[-1]
- if not pixel_format: # pragma: no cover
- pixel_format = "rgba" if with_mask else "rgb24"
+
+ pixel_format = "rgba" if with_mask else "rgb24"
# order is important
cmd = [
@@ -120,17 +120,25 @@ class FFMPEG_VideoWriter:
]
if audiofile is not None:
cmd.extend(["-i", audiofile, "-acodec", "copy"])
+
cmd.extend(["-vcodec", codec, "-preset", preset])
+
if ffmpeg_params is not None:
cmd.extend(ffmpeg_params)
+
if bitrate is not None:
cmd.extend(["-b", bitrate])
if threads is not None:
cmd.extend(["-threads", str(threads)])
- if (codec == "libx264") and (size[0] % 2 == 0) and (size[1] % 2 == 0):
- cmd.extend(["-pix_fmt", "yuv420p"])
+ # Disable auto alt ref for transparent webm and set pix format yo yuva420p
+ if codec == 'libvpx' and with_mask :
+ cmd.extend(["-pix_fmt", 'yuva420p'])
+ cmd.extend(["-auto-alt-ref", '0'])
+ elif (codec == "libx264") and (size[0] % 2 == 0) and (size[1] % 2 == 0) :
+ cmd.extend(["-pix_fmt", 'yuva420p'])
+
cmd.extend([filename])
popen_params = cross_platform_popen_params(
@@ -237,9 +245,11 @@ def ffmpeg_write_video(
logfile = open(filename + ".log", "w+")
else:
logfile = None
+
logger(message="MoviePy - Writing video %s\n" % filename)
- if not pixel_format:
- pixel_format = "rgba" if clip.mask is not None else "rgb24"
+
+ has_mask = clip.mask is not None
+
with FFMPEG_VideoWriter(
filename,
clip.size,
@@ -247,6 +257,7 @@ def ffmpeg_write_video(
codec=codec,
preset=preset,
bitrate=bitrate,
+ with_mask=has_mask,
logfile=logfile,
audiofile=audiofile,
threads=threads,
@@ -292,6 +303,7 @@ def ffmpeg_write_image(filename, image, logfile=False, pixel_format=None):
"""
if image.dtype != "uint8":
image = image.astype("uint8")
+
if not pixel_format:
pixel_format = "rgba" if (image.shape[2] == 4) else "rgb24"
diff --git a/moviepy/video/tools/drawing.py b/moviepy/video/tools/drawing.py
index 77b68b9b..cb11b817 100644
--- a/moviepy/video/tools/drawing.py
+++ b/moviepy/video/tools/drawing.py
@@ -3,10 +3,11 @@ methods that are difficult to do with the existing Python libraries.
"""
import numpy as np
+from PIL import Image
-def blit(im1, im2, pos=None, mask=None):
- """Blit an image over another.
+def blit(im1: Image, im2: Image, pos=None, mask: Image = None):
+ """Blit an image over another using pillow.
Blits ``im1`` on ``im2`` as position ``pos=(x,y)``, using the
``mask`` if provided.
@@ -16,6 +17,7 @@ def blit(im1, im2, pos=None, mask=None):
else:
# Cast to tuple in case pos is not subscriptable.
pos = tuple(pos)
+
im2.paste(im1, pos, mask)
return im2
diff --git a/tests/test_compositing.py b/tests/test_compositing.py
index 43018d74..fb42f830 100644
--- a/tests/test_compositing.py
+++ b/tests/test_compositing.py
@@ -88,26 +88,45 @@ def test_concatenate_floating_point(util):
concat.write_videofile(os.path.join(util.TMP_DIR, "concat.mp4"), preset="ultrafast")
-# def test_blit_with_opacity():
-# # bitmap.mp4 has one second R, one second G, one second B
-# clip1 = VideoFileClip("media/bitmap.mp4")
-# # overlay same clip, shifted by 1 second, at half opacity
-# clip2 = (
-# VideoFileClip("media/bitmap.mp4")
-# .subclip(1, 2)
-# .with_start(0)
-# .with_end(2)
-# .with_opacity(0.5)
-# )
-# composite = CompositeVideoClip([clip1, clip2])
-# bt = ClipPixelTest(composite)
-
-# bt.expect_color_at(0.5, (0x7F, 0x7F, 0x00))
-# bt.expect_color_at(1.5, (0x00, 0x7F, 0x7F))
-# bt.expect_color_at(2.5, (0x00, 0x00, 0xFF))
+def test_blit_with_opacity():
+ # has one second R, one second G, one second B
+ size = (2, 2)
+ clip1 = (
+ ColorClip(size, color=(255, 0, 0), duration=1)
+ + ColorClip(size, color=(0, 255, 0), duration=1)
+ + ColorClip(size, color=(0, 0, 255), duration=1)
+ )
+ # overlay green at half opacity during first 2 sec
+ clip2 = ColorClip(size, color=(0, 255, 0), duration=2).with_opacity(0.5)
+ composite = CompositeVideoClip([clip1, clip2])
+ bt = ClipPixelTest(composite)
+
+ # red + 50% green
+ bt.expect_color_at(0.5, (0x7F, 0x7F, 0x00))
+ # green + 50% green
+ bt.expect_color_at(1.5, (0x00, 0xFF, 0x00))
+ # blue is after 2s, so keep untouched
+ bt.expect_color_at(2.5, (0x00, 0x00, 0xFF))
+
+
+def test_transparent_rendering(util):
+ # Has one R 30%, one G 30%, one B 30%
+ clip1 = ColorClip((100, 100), (255, 0, 0, 76.5)).with_duration(2)
+ clip2 = ColorClip((50, 50), (0, 255, 0, 76.5)).with_duration(2)
+ clip3 = ColorClip((25, 25), (0, 0, 255, 76.5)).with_duration(2)
+
+ compostite_clip1 = CompositeVideoClip([clip1, clip2.with_position(('center', 'center'))])
+ compostite_clip2 = CompositeVideoClip([compostite_clip1, clip3.with_position(('center', 'center'))])
+
+ output_filepath = os.path.join(util.TMP_DIR, "opacity.webm")
+ compostite_clip2.write_videofile(output_filepath, fps=5)
+
+ # Load output file and check transparency
+ output_file = VideoFileClip(output_filepath, has_mask = True)
+
+
-def test_blit_with_opacity():
# has one second R, one second G, one second B
size = (2, 2)
clip1 = (
diff --git a/tests/test_issues.py b/tests/test_issues.py
index ca61cc1f..47c6826c 100644
--- a/tests/test_issues.py
+++ b/tests/test_issues.py
@@ -360,5 +360,58 @@ def test_issue_1682_2(util):
clip.write_audiofile(output_audio_filepath)
+def test_issue_2269(util):
+ filename = "media/big_buck_bunny_0_30.webm"
+ clip = VideoFileClip(filename).subclipped(0, 3)
+ color_clip = ColorClip((500, 200), (255, 0, 0, 255)).with_duration(3)
+ txt_clip_with_margin = TextClip(text="Hello", font=util.FONT, font_size=72, stroke_color="white", stroke_width=10, margin=(10,5,0,0), text_align="center").with_duration(3)
+
+ comp1 = CompositeVideoClip([color_clip, txt_clip_with_margin.with_position(("center", "center"))])
+ 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)
+ pixel = frame[334, 625]
+ assert pixel == [255, 0, 0]
+
+
+def test_issue_2269_2(util):
+ clip1 = ColorClip((200, 200), (255, 0, 0)).with_duration(3)
+ clip2 = ColorClip((100, 100), (0, 255, 0, 76.5)).with_duration(3)
+ clip3 = ColorClip((50, 50), (0, 0, 255, 76.5)).with_duration(3)
+
+ compostite_clip1 = CompositeVideoClip([clip1, clip2.with_position(('center', 'center'))])
+ compostite_clip2 = CompositeVideoClip([compostite_clip1, clip3.with_position(('center', 'center'))])
+
+ # If transparency work as expected the clip should match thoses colors
+ frame = compostite_clip2.get_frame(2)
+ pixel1 = frame[100, 10]
+ pixel2 = frame[100, 60]
+ pixel3 = frame[100, 100]
+ assert pixel1 == [255, 0, 0]
+ assert pixel2 == [179, 76, 0]
+ assert pixel3 == [126, 53, 76]
+
+
+def test_issue_2269_3(util):
+ # This time all clips have transparency
+ clip1 = ColorClip((200, 200), (255, 0, 0, 76.5)).with_duration(3)
+ clip2 = ColorClip((100, 100), (0, 255, 0, 76.5)).with_duration(3)
+ clip3 = ColorClip((50, 50), (0, 0, 255, 76.5)).with_duration(3)
+
+ compostite_clip1 = CompositeVideoClip([clip1, clip2.with_position(('center', 'center'))])
+ compostite_clip2 = CompositeVideoClip([compostite_clip1, clip3.with_position(('center', 'center'))])
+
+ # If transparency work as expected the clip transparency should be between 0.3 and 0.657
+ frame = compostite_clip2.mask.get_frame(2)
+ pixel1 = frame[100, 10]
+ pixel2 = frame[100, 60]
+ pixel3 = frame[100, 100]
+ assert pixel1 == 0.3
+ assert pixel2 == 0.51
+ assert pixel3 == 0.657
+
+
+
if __name__ == "__main__":
pytest.main()