01, Moviepy:第一个小demo

2,367 阅读2分钟

本文直接就跳过了环境安装, 没有安装的点击MoviePy - 中文文档1-下载与安装, 我当时安装都是照着这篇文章安装的.

如果你用的textClip的话(可以先不用安装, 后续用到再安装), linux下需要手动安装imagemagic, 安装教程参考centos安装ImageMagick, 在修改一下 config_default.py的最后一行, 给IMAGEMAGICK_BINARY 赋值

国际惯例, 先上代码,在细讲

code:

# coding:utf-8
from moviepy.editor import *

if __name__ == '__main__':
    # 加载视频剪辑
    video = VideoFileClip('./demo.mp4')
    # 输出视频的时长, 宽, 高, fps
    print("video time: %s, width: %s, height: %s, fps: %s" % (video.duration, video.w, video.h, video.fps))

    print('===============')
    # 跳转视频的分辨率, 时长和fps
    clip = video.resize(0.5).subclip(0, 15).set_fps(10)
    print("clip time: %s, width: %s, height: %s, fps: %s" % (clip.duration, clip.w, clip.h, clip.fps))
    print("video time: %s, width: %s, height: %s, fps: %s" % (video.duration, video.w, video.h, video.fps))
    # 将剪辑后的视频写出到文件中
    clip.write_videofile('./demo_out.mp4')

result:
video time: 2651.61, width: 1920, height: 1080, fps: 30.0
===============
clip time: 15, width: 960, height: 540, fps: 10
video time: 2651.61, width: 1920, height: 1080, fps: 30.0

1, resize(newsize, width, height)

Parameters:

  • newsize:

    Can be either (width,height) in pixels or a float representing
    A scaling factor, like 0.5
    A function of time returning one of these.

  • width: width of the new clip in pixel. The height is then computed so that the width/height ratio is conserved.

  • height: height of the new clip in pixel. The width is then computed so that the width/height ratio is conserved.

resize函数: 参数有3个, 第一个参数为新的尺寸, 第二个参数为宽, 第三个参数为高

参数1: 可以有3中表达方式, 1, (width, height) 宽高的一个元组。 2, 缩放比例。 3, 或者是一个参数为时间的表达式。 前面2个好理解, 第三个怎么回事呢? 咳 咳...超纲了, 后续再讲, 不放代码了, 就简单说一下, 就是说视频的尺寸会随着时间的变化而变化, 可以用函数来控制宽和高

参数2: 直接指定视频的宽

参数3: 直接指定视频的高

如果我们同时指定所有参数会怎么样呢? 以参数1为准

同时指定resize的参数:
以参数1 为准, 后面2个参数被忽略

# coding:utf-8
from moviepy.editor import *

if __name__ == '__main__':
    video = VideoFileClip('./demo.mp4')
    print("video time: %s, width: %s, height: %s, fps: %s" % (video.duration, video.w, video.h, video.fps))
    print('===============')
    clip = video.resize(0.5, 100, 100).subclip(0, 15).set_fps(10)
    print("clip time: %s, width: %s, height: %s, fps: %s" % (clip.duration, clip.w, clip.h, clip.fps))
    print("video time: %s, width: %s, height: %s, fps: %s" % (video.duration, video.w, video.h, video.fps))
    clip.write_videofile('./demo_out.mp4')
    
    
result:
video time: 2651.61, width: 1920, height: 1080, fps: 30.0
===============
clip time: 15, width: 960, height: 540, fps: 10
video time: 2651.61, width: 1920, height: 1080, fps: 30.0

2, clip(t_start, t_end)

返回时间在t_start ~ t_end的视频剪辑片段

时间参数格式: 1, 秒 2, (分, 秒) 3, (时, 分, 秒) 4, '时:分:秒' 。 秒可以带小数

3, write_videofile

这个方法的参数太多, 大多直接使用默认即可, 除非有更多的需求, 对于入门我们只要了解参数1 为写出的视频名即可。

4, 最后

注意大部分对视频剪辑的操作都会返回一个新的, 还不会修改原来的视频剪辑片段