Ask Your Question

How to record video using OpenCV and Python?

asked 2014-02-06 20:19:53 -0500

chutsu gravatar image

I have looked at OpenCV's Python example on how to use VideoCapture and VideoWriter to capture and write out a video file. But I keep getting:

OpenCV Error: Assertion failed ( == in cvCvtColor, file 
/tmp/opencv-n8PM/opencv-, line 4422
Traceback (most recent call last):
  File "examples/observer/", line 17, in <module>
cv2.error: /tmp/opencv-n8PM/opencv- error: 
(-215) == 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 =*'XVID')  # cv2.VideoWriter_fourcc() does not exist
    video_writer = cv2.VideoWriter("output.avi", fourcc, 20, (680, 480))

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


edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2014-02-17 19:34:32 -0500

Please make sure your input 'frame' size is equal to output video's size (in this case, (680, 480) ).

I previously got this error when the input image size is different from videowriter's out put size setting.

edit flag offensive delete link more


sigh I wish people would post more complete, helpful answers. I was able to get this to work by explicitly changing the widthxheight of the captured stream like this:

# find the webcam
capture = cv2.VideoCapture(0)


MAC OS :10.10.5 Python: 2.7.9 OpenCV: 3.1.0

frakman1 gravatar imagefrakman1 ( 2016-03-18 14:21:59 -0500 )edit

Furthermore, I had to change 'XVID' to 'MJPG' before it would play back the recorded file correctly.

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
frakman1 gravatar imagefrakman1 ( 2016-03-18 14:29:09 -0500 )edit

I could only get VideoWriter to work by using the same frame as my video capture and using this codec: mp4v (lowercase):

cap = cv2.VideoCapture(0)
w = cap.get(cv2.CAP_PROP_FRAME_WIDTH);
h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT); 
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4',fourcc, 15.0, (int(w),int(h)))

Mac OS X El Capitan 10.11.3 with Python 2.7.11, OpenCV 3.1.0

rpcarn gravatar imagerpcarn ( 2016-03-21 14:06:40 -0500 )edit
Login/Signup to Answer

Question Tools


Asked: 2014-02-06 20:19:53 -0500

Seen: 19,550 times

Last updated: Jul 21 '14