moviepy==1.0.2
正常畫中畫
#畫中畫
from moviepy.editor import VideoFileClip, CompositeVideoClip
from moviepy.video.fx.resize import resize
main_clip = VideoFileClip("1222.mp4") # 主要影片
pip_clip = VideoFileClip("122.mp4") # 畫中畫影片
pip_clip = resize(pip_clip, width=300)
pip_clip = pip_clip.set_position(("right", "bottom")).set_duration(main_clip.duration)
final_clip = CompositeVideoClip([main_clip, pip_clip])
final_clip.write_videofile("output_video.mp4", codec="libx264", fps=24)
圓形畫中畫
# 畫中畫圓形影片🆗
from moviepy.editor import VideoFileClip, CompositeVideoClip, ImageClip
import numpy as np
from moviepy.video.fx.resize import resize
# 建立圓形遮罩的函式
def create_circular_mask(width, height):
"""
建立圓形遮罩,返回一個圓形區域為白色,背景為透明的遮罩影像
"""
mask = np.zeros((height, width), dtype=np.uint8)
center = (width // 2, height // 2)
radius = min(center)
# 填充圓形區域為白色(顯示部分)
y, x = np.ogrid[:height, :width]
mask_area = (x - center[0]) ** 2 + (y - center[1]) ** 2 <= radius ** 2
mask[mask_area] = 255
return mask
# 裁剪影片併合成畫中畫的函式
def create_pip_video(pip_video_path, background_video_path, pip_position=(0, 0), pip_size=None, output_path="output_video_with_circular_pip.mp4"):
"""
裁剪 pip_video 為圓形並將其合成到背景影片上,形成畫中畫效果
:param pip_video_path: 要裁剪的畫中畫影片檔案路徑
:param background_video_path: 背景影片檔案路徑
:param pip_position: 畫中畫影片的位置,元組 (x, y)
:param pip_size: 畫中畫影片的目標大小,元組 (width, height),可選
:param output_path: 輸出影片檔案路徑
"""
# 載入 pip 影片檔案
pip_video = VideoFileClip(pip_video_path)
# 如果指定了 pip_size,則調整 pip_video 的大小
if pip_size:
pip_video = resize(pip_video,newsize=pip_size)
# 獲取調整後的影片大小
width, height = pip_video.size
# 建立圓形遮罩
mask = create_circular_mask(width, height)
mask_3d = np.stack([mask] * 3, axis=-1) # 將二維mask轉換為三維
# 將影片裁剪為圓形並設定透明背景
mask_clip = ImageClip(mask_3d).set_duration(pip_video.duration).set_fps(pip_video.fps).to_mask()
# 為影片設定遮罩
pip_video_with_mask = pip_video.set_mask(mask_clip)
background_video = VideoFileClip(background_video_path)
final_video = CompositeVideoClip([background_video, pip_video_with_mask.set_position(pip_position)])
final_video.write_videofile(output_path, codec="libx264", fps=background_video.fps)
# 呼叫函式,傳入影片路徑和引數
create_pip_video(
"122.mp4",
"1222.mp4",
pip_position=(450, 950),
pip_size=(250, 300), # 調整畫中畫影片的大小
output_path="output_video_with_circular_pip.mp4"
)