从 +250.000 帧创建 7 小时的视频

Create 7 hour video from +250.000 frames

我有 14 个 30 分钟的视频(7 小时的视频数据)。我分别读取每个视频,对每一帧进行一些形态学处理,然后使用 cv2.imwrite() 保存每个处理过的帧。我想制作 1 个包含 7 小时所有已处理帧的大视频文件。到目前为止,我一直在尝试使用此代码:

import numpy as np
import glob
 
img_array = []
for filename in glob.glob('C:/New folder/Images/*.jpg'):
    img = cv2.imread(filename)
    height, width, layers = img.shape
    size = (width,height)
    img_array.append(img)
 
 
out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, size)
 
for i in range(len(img_array)):
    out.write(img_array[i])
out.release()

但是创建img_array时报错(内存过载)。有没有其他方法可以从 +250.000 帧制作一个 7 小时的视频?

谢谢。

您不需要将每一帧都存储在一个数组中。 可以读取帧直接写入视频

您可以将代码修改为:

import numpy as np
import glob
out = None
for filename in glob.glob('C:/New folder/Images/*.jpg'):
    img = cv2.imread(filename)
    if not out:
        height, width, layers = img.shape
        size = (width,height)
        out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, size)
    out.write(img)
out.release()
  • 检查所有图片的尺寸是否相同
  • 正如其他人所说,不要一次阅读所有图片。没必要。

通常我更喜欢在循环之前创建 VideoWriter,但您需要它的大小,而且您只有在阅读第一张图片后才知道。这就是为什么我将该变量初始化为 None 并在我拥有第一张图像后创建 VideoWriter

另外:DIVX.avi 可能有效,但这不是最佳选择。内置选项是使用 MJPG(使用 .avi),它在 OpenCV 中始终可用。但是,我会为一般视频推荐 .mkvavc1 (H.264),或者您可以寻找一种无损编解码器,它以 RGB 而不是 YUV 格式存储数据(这可能会扭曲屏幕截图中的颜色信息...... .还有画线和其他硬边)。您可以尝试 rle (注意 space)编解码器,这是一种基于 运行 长度编码的无损编解码器。

import cv2 # `import cv2 as cv` is preferred these days
import numpy as np
import glob
 
out = None # VideoWriter initialized after reading the first image
outsize = None

for filename in glob.glob('C:/New folder/Images/*.jpg'):
    img = cv2.imread(filename)
    assert img is not None, filename # file could not be read

    (height, width, layers) = img.shape
    thissize = (width, height)

    if out is None: # this happens once at the beginning
        outsize = thissize
        out = cv2.VideoWriter('project.avi', cv2.VideoWriter_fourcc(*'DIVX'), 15, outsize)
        assert out.isOpened()
    else: # error checking for every following image
        assert thissize == outsize, (outsize, thissize, filename)

    out.write(img)

# finalize the video file (write headers/footers)
out.release()

您也可以通过在命令行(或从您的程序)调用 ffmpeg 来执行此操作:

How to create a video from images with FFmpeg?