Ask Your Question

Revision history [back]

I don't know if anyone out there is still having problems with this, but here are the problems I ran into and how I solved them: in opencv 3: 'cv2.VideoWriter(filename, fourcc,fps,framesize,apiPreference)'

  1. Size must be correct for framesize argument. This argument takes a tuple (x,y). X should be the width of your image, and Y the height. I recommend pulling this from the image you're working with. However, if you're dealing with a numpy array, you want to reverse the output (if you're using np.shape to get the size, for example), so the columns are x and rows are y. If the size is wrong, you will get an empty video (denoted by a fixed size file regardless of recording time/number of frames, and errors when attempting playback).

  2. The image must be in BGR format or it will not write. To do this, take your image and convert with opencv's color convertor: cv2.cvtColor(imgname,cv2.COLOR_GRAY2BGR) or cv2.cvtColor(imgname,cv2.COLOR_RGB2BGR) There are other conversion types out there. It won't make a video if it's not BGR format, though.

  3. Getting an apiPreference error (typeError)? Try setting the apiPreference to 0 (cv2.CAP_ANY) or 1900 (cv2.CAP_FFMPEG). There's a list of settings out there somewhere, I tried to find it to link it but haven't come across it again, my bad! Alternatively, you can try changing the codec for the video (fourcc). I found success with MPEG (entered as:

opencv3:cv2.VideoWriter_fourcc('M','P',E','G') older versions:'M','P,'E','G')

You can also try MJPG, XVID, and H264 if you're on Linux, like me. You have to write it in that same XXXX format as demonstrated above.

Lastly, as far as I can tell, this thing only spits out avi. A huge bummer, especially if you're shooting for lossless videos, but hey, it's better than no video at all? Eh? ::Kanye shrug::

Hope this helps.