moviepy平移效果

msms123發表於2024-12-02

使用moviepy實現了自上而下,自下而上的效果,可以根據實現各樣的效果

# 從上往下👇
from moviepy.editor import ImageClip, CompositeVideoClip
from moviepy.video.VideoClip import ColorClip

# 載入圖片A
image_a = ImageClip("right_long.png")

# 獲取圖片的尺寸
image_width, image_height = image_a.size

# 定義畫布高度
canvas_height = 500

pic_duration = image_height / canvas_height

# 建立白色背景畫布,大小為圖片寬度和設定的高度
background = ColorClip(size=(image_width, canvas_height), color=(255, 255, 255), duration=pic_duration)

# 設定圖片的持續時間
image_a = image_a.set_duration(pic_duration)

# 設定平移函式:圖片從畫布外下方平移到畫布內
def move_image(t):
    y_pos = -image_height + (image_height * t / pic_duration)  # 從畫布外平移到畫布內
    return ('center', y_pos)

# 應用平移效果
moving_image = image_a.set_position(lambda t: move_image(t))

# 合成影片:白色背景 + 平移效果的圖片
final_video = CompositeVideoClip([background, moving_image])

# 輸出影片檔案
final_video.write_videofile("from_top_to_bottom.mp4", codec="libx264", fps=24)

其中想要具體從哪裡平移到哪裡可以自己計算。
畫了一張圖可以參考

由此可以得出y_pos

自下而上

#👆
from moviepy.editor import ImageClip, CompositeVideoClip
from moviepy.video.VideoClip import ColorClip

image_a = ImageClip("right_long.png")

image_width, image_height = image_a.size

canvas_height = 500

speed_factor = 5 #越大越慢
pic_duration = (image_height / canvas_height) * speed_factor

background = ColorClip(size=(image_width, canvas_height), color=(255, 255, 255), duration=pic_duration)

image_a = image_a.set_duration(pic_duration)

def move_image(t):
    y_pos = canvas_height - (canvas_height * t / pic_duration)
    return ('center', y_pos)

moving_image = image_a.set_position(lambda t: move_image(t))
final_video = CompositeVideoClip([background, moving_image])
final_video.write_videofile("from_bottom_to_top.mp4", codec="libx264", fps=24)

相關文章