Keep transparency after merging 2 videos

17 Views Asked by At

I have a code for merging 2 videos, both with transparent backgrounds, one is a mov. file and one is a webm.(V9). I'm using Moviepy to composite both videos with the hope of preserving transparency of both so the final video would also have transparent background. The mov file retains transparency and is layered over the webm file, but the webm file doesn't seem to retain its transparency no matter what I do, and so the final file will always have a black background.

Here's my Python code


import tkinter as tk
from tkinter import filedialog
import cv2
import moviepy.editor as mpe

# Initialize Tkinter
root = tk.Tk()
root.withdraw()  # Hide the main window

# Ask user to select the lower third video file
lowerThird = filedialog.askopenfilename(title="Select Lower Third Video File",
                                        filetypes=(("MOV files", "*.mov"), ("All files", "*.*")))

# Ask user to select the main video file
videoFile = filedialog.askopenfilename(title="Select Main Video File",
                                       filetypes=(("WebM files", "*.webm"), ("All files", "*.*")))

# Ask user to choose the output file path
outputFile = filedialog.asksaveasfilename(defaultextension=".webm",
                                           filetypes=(("WebM files", "*.webm"), ("All files", "*.*")))

def vdo_with_alpha(lowerThird, videoFile, outputFile):
    tmpVid = cv2.VideoCapture(videoFile)
    framespersecond = float(tmpVid.get(cv2.CAP_PROP_FPS))

    video_clip = mpe.VideoFileClip(videoFile, has_mask=True, target_resolution=(1080, 1920), audio=False) # We set audio to False for transparency

    overlay_clip = mpe.VideoFileClip(lowerThird, has_mask=True, target_resolution=(1080, 1920))

    final_video = mpe.CompositeVideoClip([video_clip.set_duration(overlay_clip.duration), overlay_clip.set_duration(video_clip.duration)])

    final_video.write_videofile(
        outputFile,
        fps=framespersecond,
        remove_temp=True,
        codec="libvpx-vp9", # Using VP9 codec for WebM with transparency
        audio_codec="libvorbis",
        threads=6,
        preset='ultrafast', # You may need to adjust the preset for better quality
        ffmpeg_params=["-auto-alt-ref", "0", "-deadline", "1"] # We may need to adjust other ffmpeg parameters for transparency
    )

# Call the function with the selected files
if lowerThird and videoFile and outputFile:
    vdo_with_alpha(lowerThird, videoFile, outputFile)
0

There are 0 best solutions below