我有一组名为 images 的 numpy 数组图像。为了便于讨论,我们假设 -
images = [cv2.imread("data/frame" + str(i) + ".jpg") for i in range(15)]
其中数据是包含视频帧的目录。 然后我尝试使用以下代码将它们保存为视频:
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
shape = images[0].shape[:2]
vid = cv2.VideoWriter("my_vid.avi", fourcc, 1, shape)
for fg_frame in images:
vid.write(np.uint8(fg_frame))
vid.release()
但保存的视频只有 5-6 KB 大小,无法播放。我做错了什么?
最佳答案
原因是 cv2.VideoWriter
的构造函数在第 4 个参数中采用视频大小,该参数应为 (width, height)
形式的元组。
numpy
数组的 shape
成员将维度存储为 (height, width)
。
由于 VideoWriter
与实际图像尺寸不匹配,没有帧写入磁盘。
当作为参数传递给 VideoWriter
时,您必须交换 shape
的元素。正确的代码可能如下所示:
shape = images[0].shape[:2]
video_size = (shape[1], shape[0])
vid = cv2.VideoWriter("my_vid.avi", fourcc, 1, video_size)
已在 Ubuntu 14.04 上使用 Python 3 和 OpenCV 3.4 进行验证和测试。
关于python - OpenCV - 从现有图像制作视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50411092/