Video editing with Python
Massive refactor and fixing of ffmpeg reader and writer for transparency support, all transparency was actually buggy, both during rendering and reading. Also complete refactor of CompositeVideoClip compositing to properly support tranparency with CompositeVideoClip including one or more CompositeVideoClip, and transparency in general who was completly buggy
osaajani4feb4b16d629
diff --git a/moviepy/__init__.py b/moviepy/__init__.pyindex 5b0fb4fe..2b9baa8d 100644--- a/moviepy/__init__.py+++ b/moviepy/__init__.py@@ -1,13 +1,6 @@"""Imports everything that you need from the MoviePy submodules so that every thingcan be directly imported with ``from moviepy import *``."""--import debugpy-debugpy.listen(("localhost", 5678)) # Use a unique port-print("Waiting for debugger to attach...")-debugpy.wait_for_client()-print("Debugger attached.")-from moviepy.audio import fx as afxfrom moviepy.audio.AudioClip import (AudioArrayClip,diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.pyindex 80f0f6de..fdb99e32 100644--- a/moviepy/audio/io/readers.py+++ b/moviepy/audio/io/readers.py@@ -181,7 +181,6 @@ class FFMPEG_AudioReader:t = 1.0 * pos / self.fpsself.initialize(t)elif pos > self.pos:- # print posself.skip_chunk(pos - self.pos)# last case standing: pos = current posself.pos = posdiff --git a/moviepy/tools.py b/moviepy/tools.pyindex 52917b40..5eaeae3f 100644--- a/moviepy/tools.py+++ b/moviepy/tools.py@@ -233,3 +233,70 @@ def no_display_available() -> bool:return Truereturn False+++def compute_position(+ clip1_size: tuple, clip2_size: tuple, pos: any, relative: bool = False+) -> tuple[int, int]:+ """Return the position to put clip 1 on clip 2 based on both clip size+ and the position of clip 1, as return by clip1.pos() method++ Parameters+ ----------+ clip1_size : tuple+ The width and height of clip1 (e.g., (width, height)).+ clip2_size : tuple+ The width and height of clip2 (e.g., (width, height)).+ pos : Any+ The position of clip1 as returned by the `clip1.pos()` method.+ relative: bool+ Is the position relative (% of clip size), default False.++ Returns+ -------+ tuple[int, int]+ A tuple (x, y) representing the top-left corner of clip1 relative to clip2.++ Notes+ -----+ For more information on `pos`, see the documentation for `VideoClip.with_position`.+ """+ if pos is None:+ pos = (0, 0)++ # 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 relative:+ for i, dim in enumerate(clip2_size):+ if not isinstance(pos[i], str):+ pos[i] = dim * pos[i]++ if isinstance(pos[0], str):+ D = {+ "left": 0,+ "center": (clip2_size[0] - clip1_size[0]) / 2,+ "right": clip2_size[0] - clip1_size[0],+ }+ pos[0] = D[pos[0]]++ if isinstance(pos[1], str):+ D = {+ "top": 0,+ "center": (clip2_size[1] - clip1_size[1]) / 2,+ "bottom": clip2_size[1] - clip1_size[1],+ }+ pos[1] = D[pos[1]]++ # Return as int, rounding if necessary+ return (int(pos[0]), int(pos[1]))diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex a76e0daf..e571602d 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -34,13 +34,12 @@ from moviepy.decorators import (requires_fps,use_clip_fps_by_default,)-from moviepy.tools import extensions_dict, find_extension+from moviepy.tools import extensions_dict, find_extension, compute_positionfrom moviepy.video.fx.Crop import Cropfrom moviepy.video.fx.Resize import Resizefrom moviepy.video.fx.Rotate import Rotatefrom moviepy.video.io.ffmpeg_writer import ffmpeg_write_videofrom moviepy.video.io.gif_writers import write_gif_with_imageio-from moviepy.video.tools.drawing import blitclass VideoClip(Clip):@@ -714,134 +713,123 @@ class VideoClip(Clip):post_array = np.hstack((post_array, x_1))return post_array- def blit_on(self, picture, t):- """Returns the result of the blit of the clip's frame at time `t`+ def compose_on(self, background: Image.Image, t) -> Image.Image:+ """Returns the result of the clip's frame at time `t` on topon the given `picture`, the position of the clip being givenby 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+ If the clip/backgrounds have transparency the transparency will+ be accounted for.++ The return is a Pillow Image++ Parameters+ -----------+ backrgound (Image)+ The background image to apply current clip on top of+ if the background image is transparent it must be given as a RGBA image+ t+ The time of clip to apply on top of clip++ Return+ """ct = t - self.start # clip time# GET IMAGE AND MASK IF ANY- img = self.get_frame(ct).astype("uint8")- im_img = Image.fromarray(img)+ clip_frame = self.get_frame(ct).astype("uint8")+ clip_img = Image.fromarray(clip_frame)if self.mask is not None:- mask = (self.mask.get_frame(ct) * 255).astype("uint8")- im_mask = Image.fromarray(mask).convert("L")+ clip_mask = (self.mask.get_frame(ct) * 255).astype("uint8")+ clip_mask_img = Image.fromarray(clip_mask).convert("L")- if im_img.size != im_mask.size:- bg_size = (- max(im_img.size[0], im_mask.size[0]),- max(im_img.size[1], im_mask.size[1]),- )+ # Resize clip_mask_img to match clip_img, always use top left corner+ if clip_mask_img.size != clip_img.size:+ mask_width, mask_height = clip_mask_img.size+ img_width, img_height = clip_img.size- im_img_bg = Image.new("RGB", bg_size, "black")- im_img_bg.paste(im_img, (0, 0))-- im_mask_bg = Image.new("L", bg_size, 0)- im_mask_bg.paste(im_mask, (0, 0))+ if mask_width > img_width or mask_height > img_height:+ # Crop mask if it is larger+ clip_mask_img = clip_mask_img.crop((0, 0, img_width, img_height))+ else:+ # Fill mask with 0 if it is smaller+ new_mask = Image.new("L", (img_width, img_height), 0)+ new_mask.paste(clip_mask_img, (0, 0))+ clip_mask_img = new_mask- im_img, im_mask = im_img_bg, im_mask_bg- else:- im_mask = None+ clip_img = clip_img.convert("RGBA")+ clip_img.putalpha(clip_mask_img)- wi, hi = im_img.size# SET POSITIONpos = self.pos(ct)+ pos = compute_position(clip_img.size, background.size, pos, self.relative_pos)++ # If neither background nor clip have alpha layer (check if mode end+ # with A), we can juste use pillow paste+ if clip_img.mode[-1] != "A" and background.mode[-1] != "A":+ background.paste(clip_img, pos)+ 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+ if background.mode[-1] != "A":+ background = background.convert("RGBA")++ if clip_img.mode[-1] != "A":+ clip_img = clip_img.convert("RGBA")++ # We need both image to do the same size for alpha compositing in pillow+ # 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))+ canvas.paste(clip_img, pos)+ result = Image.alpha_composite(background, canvas)+ return result- # 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([wf, hf]):- if not isinstance(pos[i], str):- pos[i] = dim * pos[i]-- if isinstance(pos[0], str):- D = {"left": 0, "center": (wf - wi) / 2, "right": wf - wi}- pos[0] = D[pos[0]]-- if isinstance(pos[1], str):- D = {"top": 0, "center": (hf - hi) / 2, "bottom": hf - hi}- pos[1] = D[pos[1]]-- 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+ def compose_mask(self, background_mask: np.ndarray, t: float) -> np.ndarray:+ """Returns the result of the clip's mask at time `t` composited+ on the given `background_mask`, the position of the clip being givenby 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)+ Parameters+ ----------+ background_mask:+ The underlying mask onto which the clip mask will be composed.++ t:+ The time position in the clip at which to extract the mask."""ct = t - self.start # clip timeclip_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+ bg_h, bg_w = background_mask.shape+ clip_h, clip_w = clip_mask.shape# SET POSITIONpos = 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]])+ pos = compute_position((clip_w, clip_h), (bg_w, bg_h), pos, self.relative_pos)# 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+ x_start = int(max(pos[0], 0)) # Dont go under 0 left+ x_end = int(min(pos[0] + clip_w, bg_w)) # Dont go over base_mask width+ y_start = int(max(pos[1], 0)) # Dont go under 0 top+ y_end = int(min(pos[1] + clip_h, bg_h)) # 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+ # 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))+ clip_x_start = int(max(0, -pos[0]))+ clip_x_end = int(clip_x_start + min((x_end - x_start), (clip_w - 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))+ clip_y_start = int(max(0, -pos[1]))+ clip_y_end = int(clip_y_start + min((y_end - y_start), (clip_h - clip_y_start)))# Blend the overlapping regions# The calculus is base_opacity + clip_opacity * (1 - base_opacity)@@ -858,15 +846,13 @@ class VideoClip(Clip):# 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])+ background_mask[y_start:y_end, x_start:x_end] = background_mask[+ y_start:y_end, x_start:x_end+ ] + clip_mask[clip_y_start:clip_y_end, clip_x_start:clip_x_end] * (+ 1 - background_mask[y_start:y_end, x_start:x_end])- return base_mask--+ return background_maskdef with_background_color(self, size=None, color=(0, 0, 0), pos=None, opacity=None):"""Place the clip on a colored background.@@ -944,10 +930,20 @@ class VideoClip(Clip):@outplacedef with_mask(self, mask: Union["VideoClip", str] = "auto"):- """Set the clip's mask.+ """+ Set the clip's mask.Returns a copy of the VideoClip with the mask attribute set to``mask``, which must be a greyscale (values in 0-1) VideoClip.++ Parameters+ ----------+ mask : Union["VideoClip", str], optional+ The mask to apply to the clip.+ If set to "auto", a default mask will be generated:+ - If the clip has a constant size, a solid mask with a value of 1.0+ will be created.+ - Otherwise, a dynamic solid mask will be created based on the frame size."""if mask == "auto":if self.has_constant_size:diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.pyindex 174fdaf9..d38c3f6e 100644--- a/moviepy/video/compositing/CompositeVideoClip.py+++ b/moviepy/video/compositing/CompositeVideoClip.py@@ -59,19 +59,18 @@ class CompositeVideoClip(VideoClip):if size is None:size = clips[0].size- if not use_bgclip and bg_color is None :- use_bgclip = True-if use_bgclip and (clips[0].mask is None):transparent = False+ else:+ transparent = True if bg_color is None else False- # If we must not use fist clip as background and we dont have a color- # we generate a black background if clip should not be transparent and+ # If we must not use first clip as background and we dont have a color+ # we generate a black background if clip should not be transparent and# a transparent background if transparentif (not use_bgclip) and bg_color is None:- if transparent :+ if transparent:bg_color = 0.0 if is_mask else (0, 0, 0, 0)- else :+ else:bg_color = 0.0 if is_mask else (0, 0, 0)fpss = [clip.fps for clip in clips if getattr(clip, "fps", None)]@@ -90,7 +89,7 @@ class CompositeVideoClip(VideoClip):self.bg = clips[0]self.clips = clips[1:]self.created_bg = False- else :+ else:self.clips = clipsself.bg = ColorClip(size, color=self.bg_color, is_mask=is_mask)self.created_bg = True@@ -121,32 +120,64 @@ class CompositeVideoClip(VideoClip):for clip in self.clips]+ if use_bgclip and self.bg.mask:+ maskclips = [self.bg.mask] + maskclips+self.mask = CompositeVideoClip(maskclips, self.size, is_mask=True, bg_color=0.0)def frame_function(self, t):"""The clips playing at time `t` are blitted over one another."""- 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 :+ # For the mask we recalculate the final transparency will need+ # to apply on the result image+ 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+ mask = clip.compose_mask(mask, t)- if self.bg.mask is not None:- frame_mask = self.bg.mask.get_frame(t)- im_mask = Image.fromarray(255 * frame_mask).convert("L")- im.putalpha(im_mask)+ return mask+ # Try doing clip merging with pillow+ bg_t = t - self.bg.start+ bg_frame = self.bg.get_frame(bg_t).astype("uint8")+ bg_img = Image.fromarray(bg_frame)++ if self.bg.mask:+ bgm_t = t - self.bg.mask.start+ bg_mask = (self.bg.mask.get_frame(bgm_t) * 255).astype("uint8")+ bg_mask_img = Image.fromarray(bg_mask).convert("L")++ # Resize bg_mask_img to match bg_img, always use top left corner+ if bg_mask_img.size != bg_img.size:+ mask_width, mask_height = bg_mask_img.size+ img_width, img_height = bg_img.size++ if mask_width > img_width or mask_height > img_height:+ bg_mask_img = bg_mask_img.crop((0, 0, img_width, img_height))+ else:+ new_mask = Image.new("L", (img_width, img_height), 0)+ new_mask.paste(bg_mask_img, (0, 0))+ bg_mask_img = new_mask++ bg_img = bg_img.convert("RGBA")+ bg_img.putalpha(bg_mask_img)++ # For each clip apply on top of current img+ current_img = bg_imgfor clip in self.playing_clips(t):- im = clip.blit_on(im, t)+ current_img = clip.compose_on(current_img, t)++ # Turn Pillow image into a numpy array+ frame = np.array(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]- return np.array(im)+ return framedef playing_clips(self, t=0):"""Returns a list of the clips in the composite clips that arediff --git a/moviepy/video/fx/Scroll.py b/moviepy/video/fx/Scroll.pyindex 1d469d11..d5c9d60a 100644--- a/moviepy/video/fx/Scroll.py+++ b/moviepy/video/fx/Scroll.py@@ -30,7 +30,6 @@ class Scroll(Effect):y_start=0,apply_to="mask",):-self.w = wself.h = hself.x_speed = x_speeddiff --git a/moviepy/video/io/VideoFileClip.py b/moviepy/video/io/VideoFileClip.pyindex 67ec8cf5..0eccdb58 100644--- a/moviepy/video/io/VideoFileClip.py+++ b/moviepy/video/io/VideoFileClip.py@@ -105,6 +105,7 @@ class VideoFileClip(VideoClip):# Make a readerif not pixel_format:pixel_format = "rgba" if has_mask else "rgb24"+self.reader = FFMPEG_VideoReader(filename,decode_file=decode_file,diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.pyindex daa2625a..946fd54d 100644--- a/moviepy/video/io/ffmpeg_reader.py+++ b/moviepy/video/io/ffmpeg_reader.py@@ -99,13 +99,13 @@ class FFMPEG_VideoReader:i_arg = ["-i", self.filename]# For webm video (vp8 and vp9) with transparent layer, force libvpx/libvpx-vp9 as ffmpeg- # native webm decoder dont decode alpha layer+ # native webm decoder dont decode alpha layer# (see https://www.reddit.com/r/ffmpeg/comments/fgpyfb/help_with_webm_with_alpha_channel/)- if self.depth == 4 :- codec_name = self.infos.get('video_codec_name')- if codec_name == 'vp9' :+ if self.depth == 4:+ codec_name = self.infos.get("video_codec_name")+ if codec_name == "vp9":i_arg = ["-c:v", "libvpx-vp9"] + i_arg- elif codec_name == 'vp8' :+ elif codec_name == "vp8":i_arg = ["-c:v", "libvpx"] + i_argprint(self.infos)@@ -474,12 +474,12 @@ class FFmpegInfosParser:# for default streams, set their numbers globally, so it's# easy to get without iterating allif self._current_stream["default"]:- self.result[f"default_{stream_type_lower}_input_number"] = (- input_number- )- self.result[f"default_{stream_type_lower}_stream_number"] = (- stream_number- )+ self.result[+ f"default_{stream_type_lower}_input_number"+ ] = input_number+ self.result[+ f"default_{stream_type_lower}_stream_number"+ ] = stream_number# exit chapterif self._current_chapter:@@ -710,13 +710,10 @@ class FFmpegInfosParser:r"Video:\s(\w+)?\s?(\([^)]+\))?",line.lstrip(),)- if main_info_match is not None :- (- codec_name,- profile- ) = main_info_match.groups()- stream_data['codec_name'] = codec_name- stream_data['profile'] = profile+ if main_info_match is not None:+ (codec_name, profile) = main_info_match.groups()+ stream_data["codec_name"] = codec_name+ stream_data["profile"] = profileif self._current_stream["default"] or "video_codec_name" not in self.result:global_data["video_codec_name"] = stream_data.get("codec_name", None)diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.pyindex 632e6edc..8d8f22f4 100644--- a/moviepy/video/io/ffmpeg_writer.py+++ b/moviepy/video/io/ffmpeg_writer.py@@ -120,9 +120,9 @@ 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)@@ -133,11 +133,11 @@ class FFMPEG_VideoWriter:cmd.extend(["-threads", str(threads)])# 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'])+ 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])@@ -245,11 +245,11 @@ def ffmpeg_write_video(logfile = open(filename + ".log", "w+")else:logfile = None-+logger(message="MoviePy - Writing video %s\n" % filename)-+has_mask = clip.mask is not None-+with FFMPEG_VideoWriter(filename,clip.size,diff --git a/moviepy/video/tools/drawing.py b/moviepy/video/tools/drawing.pyindex cb11b817..cfbd1965 100644--- a/moviepy/video/tools/drawing.py+++ b/moviepy/video/tools/drawing.py@@ -6,22 +6,6 @@ import numpy as npfrom PIL import Image-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.- """- if pos is None:- pos = (0, 0) # pragma: no cover- else:- # Cast to tuple in case pos is not subscriptable.- pos = tuple(pos)-- im2.paste(im1, pos, mask)- return im2--def color_gradient(size,p1,diff --git a/tests/test_VideoFileClip.py b/tests/test_VideoFileClip.pyindex db06d460..4ee33cff 100644--- a/tests/test_VideoFileClip.py+++ b/tests/test_VideoFileClip.py@@ -83,5 +83,20 @@ def test_videofileclip_safe_deepcopy(monkeypatch):assert copy.deepcopy(clip) == "foo"+def test_ffmpeg_transparency_mask(util):+ """Test VideoFileClip and FFMPEG reading of video with transparency."""+ video_file = "media/transparent.webm"++ video = VideoFileClip(video_file, has_mask=True)++ assert video.mask is not None++ mask_frame = video.mask.get_frame(0)+ assert mask_frame[100, 100] == 1.0+ assert mask_frame[10, 10] == 0++ video.close()++if __name__ == "__main__":pytest.main()diff --git a/tests/test_compositing.py b/tests/test_compositing.pyindex fb42f830..b4749c59 100644--- a/tests/test_compositing.py+++ b/tests/test_compositing.py@@ -110,42 +110,69 @@ def test_blit_with_opacity():bt.expect_color_at(2.5, (0x00, 0x00, 0xFF))-def test_transparent_rendering(util):+def test_compositing_masks(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)+ compostite_clip1 = CompositeVideoClip(+ [clip1, clip2.with_position(("center", "center"))]+ )+ compostite_clip2 = CompositeVideoClip(+ [compostite_clip1, clip3.with_position(("center", "center"))]+ )# Load output file and check transparency- output_file = VideoFileClip(output_filepath, has_mask = True)+ frame = compostite_clip2.mask.get_frame(1)-+ # We check opacity with one, two and three layers+ # Allow for a bit of tolerance (about 1%) to account+ # for rounding errors+ opacity1 = frame[50, 10]+ opacity2 = frame[50, 30]+ opacity3 = frame[50, 50]+ assert abs(opacity1 - 0.3) < 0.01+ assert abs(opacity2 - 0.51) < 0.01+ assert abs(opacity3 - 0.657) < 0.01- # 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)+def test_compositing_with_transparency_colors(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)- # 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))+ compostite_clip1 = CompositeVideoClip(+ [clip1, clip2.with_position(("center", "center"))]+ )+ compostite_clip2 = CompositeVideoClip(+ [compostite_clip1, clip3.with_position(("center", "center"))]+ )++ # Load output file and check transparency+ frame = compostite_clip2.get_frame(1)+ mask = compostite_clip2.mask.get_frame(1)++ # We check color with 1 layer+ # We add a bit of tolerance (about 1%) to account+ # For possible rounding errors+ color1 = frame[50, 10]+ opacity1 = mask[50, 10]+ assert np.allclose(color1, [255, 0, 0], rtol=0.01)+ 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=0.01)+ assert abs(opacity2 - 0.51) < 0.01++ # With 3 layers+ color3 = frame[50, 50]+ opacity3 = mask[50, 50]+ assert np.allclose(color3, [57, 82, 116], rtol=0.01)+ assert abs(opacity3 - 0.657) < 0.01def test_slide_in():diff --git a/tests/test_ffmpeg_reader.py b/tests/test_ffmpeg_reader.pyindex 48b583c1..40a520c1 100644--- a/tests/test_ffmpeg_reader.py+++ b/tests/test_ffmpeg_reader.py@@ -771,12 +771,12 @@ def test_failure_to_release_file(util):def test_read_transparent_video():- reader = FFMPEG_VideoReader("media/transparent.webm", pixel_format='rgba')+ reader = FFMPEG_VideoReader("media/transparent.webm", pixel_format="rgba")# Get first frameframe = reader.get_frame(0)mask = frame[:, :, 3]-+# Check transparency on fully transparent part is 0assert mask[10, 10] == 0diff --git a/tests/test_ffmpeg_writer.py b/tests/test_ffmpeg_writer.pyindex 0985b61d..433cc795 100644--- a/tests/test_ffmpeg_writer.py+++ b/tests/test_ffmpeg_writer.py@@ -231,3 +231,25 @@ def test_write_gif(util, clip_class, loop, with_mask):assert r == 0assert g == 0assert b == 255+++def test_transparent_video(util):+ # Has one R 30%+ clip = ColorClip((100, 100), (255, 0, 0, 76.5)).with_duration(2)+ filename = os.path.join("/home/ajani/Téléchargements", "opacity.webm")++ ffmpeg_write_video(clip, filename, codec="libvpx", fps=5)++ # Load output file and check transparency+ result = VideoFileClip(filename, has_mask=True)++ # Check for mask+ assert result.mask is not None++ # Check correct opacity, allow for some tolerance (about 1%)+ # to consider rounding and compressing error+ frame = result.mask.get_frame(1)+ opacity = frame[50, 50]+ assert abs(opacity - 0.3) < 0.01++ result.close()diff --git a/tests/test_issues.py b/tests/test_issues.pyindex 47c6826c..a1bca32f 100644--- a/tests/test_issues.py+++ b/tests/test_issues.py@@ -1,6 +1,7 @@"""Issue tests meant to be run with pytest."""import os+import numpy as npimport pytest@@ -201,7 +202,6 @@ def test_issue_334(util):now = t - last_move[0]w = (lis[0][1] - last_move[1]) * (now / dura)h = (lis[0][2] - last_move[2]) * (now / dura)- # print t, last_move[1] + w, last_move[2] + hreturn (last_move[1] + w, last_move[2] + h)return (last_move[1], last_move[2])@@ -219,7 +219,6 @@ def test_issue_334(util):s = (lis1[0][3] - last_move1[3]) * (now / dura)nsw = last_move1[3] + snsh = nsw * 1.33- # print t, nsw, nshreturn (nsw, nsh)return (last_move1[3], last_move1[3] * 1.33)@@ -364,15 +363,28 @@ 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"))])+ 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 secondsframe = comp2.get_frame(2)pixel = frame[334, 625]- assert pixel == [255, 0, 0]++ # We add a bit of tolerance (about 1%) to account+ # For possible rounding errors+ assert np.allclose(pixel, [255, 0, 0], rtol=0.01)def test_issue_2269_2(util):@@ -380,17 +392,24 @@ def test_issue_2269_2(util):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'))])+ 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 colorsframe = 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]++ # We add a bit of tolerance (about 1%) to account+ # For possible rounding errors+ assert np.allclose(pixel1, [255, 0, 0], rtol=0.01)+ assert np.allclose(pixel2, [179, 76, 0], rtol=0.01)+ assert np.allclose(pixel3, [126, 53, 76], rtol=0.01)def test_issue_2269_3(util):@@ -399,8 +418,12 @@ def test_issue_2269_3(util):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'))])+ 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.657frame = compostite_clip2.mask.get_frame(2)@@ -412,6 +435,5 @@ def test_issue_2269_3(util):assert pixel3 == 0.657-if __name__ == "__main__":pytest.main()