最近工作上需要一些指定尺寸和帧率的样本视频用于测试,所以写了个自动生成视频的脚本,为了能看出视频的播放进度,视频内容是自动显示秒针计数。

用法:

生成一个1920x1080,25fps,长度40秒的视频,文件大小只有341KB,用法如下。

1
python make_video.py -w 1920 -H 1080 -f 25 -s 40 -p .

运行后在当前目录生成一个 video-1920x1080-fps25-40s.mp4 的视频文件。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import cv2
import numpy as np
import os
import optparse

def make_video(width, height, fps, seconds, path=None):
    if not path:
        path = os.path.split(os.path.realpath(__file__))[0]
    filename = 'video-{}x{}-fps{}-{}s.mp4'.format(
            width, height, fps, seconds)
    fp = os.path.join(path, filename)
    videoWriter = cv2.VideoWriter(
        fp, cv2.VideoWriter_fourcc(*'x264'), fps, (width, height))

    for i in range(1, seconds+1):
        img = np.zeros((height, width, 3), np.uint8)
        img.fill(200)
        txt1 = str(i)
        txt2 = '{} x {}'.format(width, height)
        res = cv2.putText(img, txt1, (int(width/2-120*len(txt1)), int(height/2)),
                        cv2.FONT_ITALIC, 10, (20, 20, 20), 10)
        res = cv2.putText(img, txt2, (int(width/2-len(txt2)*20), int(height/2+100)),
                        cv2.FONT_ITALIC, 1.8, (20, 20, 20), 3)

        # 如下让每张图显示1秒,具体与fps相等
        for i in range(fps):
            videoWriter.write(res)

    videoWriter.release()

if __name__ == '__main__':
    
    parser = optparse.OptionParser()
    parser.add_option("-w", "--width", dest="width", help="视频宽度", type="int")
    parser.add_option("-H", "--height", dest="height", help="视频高度", type="int")
    parser.add_option("-f", "--fps", dest="fps", help="视频每秒帧数", type="int")
    parser.add_option("-s", "--second", dest="second",
                      help="视频时间长度,单位秒", type="int")
    parser.add_option("-p", "--path", dest="path", help="视频保存目录,不包括文件名", default=None)
    (options, args) = parser.parse_args()
    make_video(options.width, options.height,
               options.fps, options.second, options.path)

代码gist地址

视频展示: