Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

python - How to concatenate videos in moviepy?

I am trying to use moviepy to generate video with texts. First, I want to show one messages and then another one. In my case I want to show "Dog" for one second and than "Cat Cat". For that I use the following code:

from 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)

This is the result that I get:

enter image description here

Does anybody know why do I have problems with cats?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To be written to a file, all the frames must have the same size. Here you frames with Dog are smaller that the frames with CatCat, which spoils the video. A first solution is to use the method "compose" in concatenate_videoclips, this will give the same size to all clips:

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")

A second solution is to give the same size (width, height) to all of your text clips:

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...