如何在moviepy中连接视频?

时间:2015-02-27 05:55:40

标签: python animation concatenation moviepy

我正在尝试使用moviepy生成带有文本的视频。首先,我想显示一条消息,然后显示另一条消息。在我的情况下,我想展示" Dog"一秒钟而不是#Cat; Cat Cat"。为此,我使用以下代码:

来自moviepy.editor import *

def my_func(messeges):

    clips = {}
    count = 0
    for messege in messeges:
        count += 1
        clips[count] = TextClip(messege, fontsize=270, color='green')
        clips[count] = clips[count].set_pos('center').set_duration(1)
        clips[count].write_videofile(str(count) + '.avi', fps=24, codec='mpeg4')

    videos = [clips[i+1] for i in range(count)]
    video = concatenate(videos)
    video.write_videofile('test.avi', fps=24, codec='mpeg4')

    video = VideoFileClip('test.avi')
    video.write_gif('test.gif', fps=24)

if __name__ == '__main__':

    ms  = []    
    ms += ['Dog']
    ms += ['Cat Cat']
    my_func(ms)

这是我得到的结果:

enter image description here

有人知道我为什么会遇到猫的问题吗?

1 个答案:

答案 0 :(得分:14)

要写入文件,所有帧必须具有相同的大小。在这里,使用Dog的框架比使用CatCat的框架小,这会破坏视频。第一个解决方案是在concatenate_videoclips中使用“compose”方法,这将为所有剪辑提供相同的大小:

import moviepy.editor as mp
messages = ["Dog", "Cat", "Duck", "Wolf"]
clips = [ mp.TextClip(txt, fontsize=170, color='green').set_duration(1)
          for txt in messages ]
concat_clip = mp.concatenate_videoclips(clips, method="compose")
concat_clip.write_videofile("texts.mp4")

第二种解决方案是为所有文本片段提供相同的大小(宽度,高度):

import moviepy.editor as mp
messages = ["Dog", "Cat", "Duck", "Wolf"]
clips = [ mp.TextClip(txt, fontsize=170, color='green', size=(500,300))
            .set_duration(1)
          for txt in  messages]
concat_clip = mp.concatenate_videoclips(clips)
concat_clip.write_videofile("texts.mp4")