如何使用 OpenCV 和 Python 录制视频?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21610294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to record video using OpenCV and Python?
提问by chutsu
I have looked at OpenCV's Python exampleon how to use VideoCaptureand VideoWriterto capture and write out a video file. But I keep getting:
我查看了 OpenCV 的Python 示例,了解如何使用VideoCapture以及VideoWriter捕获和写出视频文件。但我不断得到:
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
Cleaned up camera.
清理相机。
Here is the code:
这是代码:
#!/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()
采纳答案by mpark
The size of the frames is probably incorrect:
帧的大小可能不正确:
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))
worked for me
为我工作
回答by Sebastian Schmitz
In C++ if you can pass -1 for the codec. Then you can choose the codec by hand from all codecs on your machine. Might be the same in python, i can't find it in the documentation though.
在 C++ 中,如果您可以为编解码器传递 -1。然后您可以从机器上的所有编解码器中手动选择编解码器。在python中可能相同,但我在文档中找不到它。
video_writer = cv2.VideoWriter("output.avi", -1, 20, (680, 480))
Try it to make sure that opencv can find XVID on your machine.
尝试确保 opencv 可以在您的机器上找到 XVID。
回答by Dmytriy Voloshyn
I faced similar problem. You should debug if the problem is in frame sizes and colors' depth or in you codec. Try writing empty array into the file:
我遇到了类似的问题。您应该调试问题是在帧大小和颜色深度还是在您的编解码器中。尝试将空数组写入文件:
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))
...

