如何使用OpenCV和Python录制视频?

时间:2014-02-06 17:49:20

标签: python opencv video-recording

我查看了OpenCV Python example有关如何使用VideoCaptureVideoWriter来捕获和写出视频文件的信息。但我一直在说:

OpenCV Error: Assertion failed (dst.data == dst0.data) in cvCvtColor, file 
/tmp/opencv-n8PM/opencv-2.4.7.1/modules/imgproc/src/color.cpp, line 4422
Traceback (most recent call last):
  File "examples/observer/observer.py", line 17, in <module>
    video_writer.write(frame)
cv2.error: /tmp/opencv-n8PM/opencv-2.4.7.1/modules/imgproc/src/color.cpp:4422: error: 
(-215) dst.data == dst0.data in function cvCvtColor

清理相机。

以下是代码:

#!/usr/bin/env python import cv2


if __name__ == "__main__":
    # find the webcam
    capture = cv2.VideoCapture(0)

    # video recorder
    fourcc = cv2.cv.CV_FOURCC(*'XVID')  # cv2.VideoWriter_fourcc() does not exist
    video_writer = cv2.VideoWriter("output.avi", fourcc, 20, (680, 480))

    # record video
    while (capture.isOpened()):
        ret, frame = capture.read()
        if ret:
            video_writer.write(frame)
            cv2.imshow('Video Stream', frame)

        else:
            break

    capture.release()
    video_writer.release()
    cv2.destroyAllWindows()

3 个答案:

答案 0 :(得分:8)

帧的大小可能不正确:

w=int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH ))
h=int(capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT ))
# video recorder
fourcc = cv2.cv.CV_FOURCC(*'XVID')  # cv2.VideoWriter_fourcc() does not exist
video_writer = cv2.VideoWriter("output.avi", fourcc, 25, (w, h))

为我工作

答案 1 :(得分:4)

在C ++中,如果你可以为编解码器传递-1。然后,您可以从计算机上的所有编解码器手动选择编解码器。在python中可能是相同的,但我在文档中找不到它。

video_writer = cv2.VideoWriter("output.avi", -1, 20, (680, 480))

尝试确保opencv可以在您的计算机上找到XVID。

答案 2 :(得分:4)

我遇到了类似的问题。 如果问题是框架大小和颜色,你应该调试&#39;深度或在你的编解码器。尝试将空数组写入文件:

capSize = (100, 100) # this is the size of my source video
fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')
out = cv2.VideoWriter('output.mov',fourcc, 1, capSize)
...
out.write(125 * np.ones((100,100,3), np.uint8)) 
...