使用OpenCV从numpy数组制作MP4视频时出现断言错误

时间:2018-08-24 16:08:40

标签: numpy opencv mp4 fourcc

我有以下应该制作视频的python代码:

import cv2
import numpy as np

out = cv2.VideoWriter("/tmp/test.mp4",
                      cv2.VideoWriter_fourcc(*'MP4V'),
                      25,
                      (500, 500),
                      True)
data = np.zeros((500,500,3))
for i in xrange(500):
    out.write(data)

out.release()

我希望看到黑色视频,但代码会引发断言错误:

$ python test.py
OpenCV(3.4.1) Error: Assertion failed (image->depth == 8) in writeFrame, file /io/opencv/modules/videoio/src/cap_ffmpeg.cpp, line 274
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    out.write(data)
cv2.error: OpenCV(3.4.1) /io/opencv/modules/videoio/src/cap_ffmpeg.cpp:274: error: (-215) image->depth == 8 in function writeFrame

我尝试了各种fourcc值,但似乎没有任何作用。

2 个答案:

答案 0 :(得分:2)

根据@ jeru-luke和@ dan-masek的评论:

import cv2
import numpy as np

out = cv2.VideoWriter("/tmp/test.mp4",
                      cv2.VideoWriter_fourcc(*'mp4v'),
                      25,
                      (1000, 500),
                      True)

data = np.transpose(np.zeros((1000, 500,3), np.uint8), (1,0,2))
for i in xrange(500):
    out.write(data)

out.release()

答案 1 :(得分:2)

问题是调用np.zeros时没有指定元素的数据类型。如文档所述,默认情况下numpy将使用float64

>>> import numpy as np
>>> np.zeros((500,500,3)).dtype
dtype('float64')

但是,VideoWriter实现仅支持8位图像深度(如错误消息的“(image-> depth == 8)”部分所示)。

解决方案很简单-指定适当的数据类型,在这种情况下为uint8

data = np.zeros((500,500,3), dtype=np.uint8)