首页 > 解决方案 > 逐帧存储视频以进行视频编辑的最佳方法是什么?

问题描述

我正在尝试创建一个视频编辑器,显然,您将能够删除和添加帧。我的想法是将视频文件本身转换为一组帧,然后可以对其进行操作。

使用这个答案代码,我做到了。这适用于小视频文件,但对于大视频文件,内存错误可能很快发生 - 因为,当然,内存正在存储数百个未压缩的图像。

这是我正在使用的确切代码:

import numpy
import cv2

def video_to_frames(file):
    """Splits a video file into a numpy array of frames"""
    
    video = cv2.VideoCapture(file)
    frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
    frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
    
    buffer = numpy.empty((frame_count, frame_height, frame_width, 3), numpy.dtype("uint8"))
    index_count = 0
    running = True

    while(index_count < frame_count and running): #Reads each frame to the array
        running, buffer[index_count] = video.read()
        index_count += 1
    video.release()
    
    return buffer #Returns the numpy array of frames


print(video_to_frames("Video.mp4"))

最后,这是我得到的确切内存错误:MemoryError: Unable to allocate 249. GiB for an array with shape (46491, 1000, 1920, 3) and data type uint8

所以我真的有两个问题:

  1. 这是处理视频的最有效方法吗?
  2. 如果是,我怎样才能在不发生内存错误的情况下存储所有这些帧?

谢谢你。

标签: pythonvideocv2

解决方案


推荐阅读