Writing Video with OpenCV, Python and OSX
A lot of sources on the internet will suggest that to write a video file to disk using OpenCV, you’ll create a VideoWriter object like this:
# Define the codec and create VideoWriter Object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (1280, 720))
In this case, we’re saving a video at 20fps and 1280×720 resolution using the XVID MPEG-4 codec. This caused all sorts of problems for me. For one, there is no such thing as VideoWriter_fourcc within more up to date versions of OpenCV – the common solution being to instead use cv.CV_FOURCC. After a lot of hunting, the only working solution I’ve found was here. Below is a minimal example:
# Create a video capture object and set some parameters
cap = cv2.VideoCapture("input.mp4")
fps = 30.0
capsize = (1280, 720)
# Define the codec and create VideoWriter Object
fourcc = cv2.cv.CV_FOURCC('m', 'p','4','v')
out = cv2.VideoWriter()
success = out.open('output.mov', fourcc, fps, capsize, True)
Note that the resolution of the output has to match that of any input you use – in this case a 1280×720.
Codec Codes
A summary of Video Writer performance on OS X using different codecs (four character codes - fourcc) can be found here. The TL;DR is use either mp4v or avc1.