OpenCV write frame to file python

preezzzy picture preezzzy · Oct 19, 2014 · Viewed 7.6k times · Source

Hey so im starting to play around with OpenCV and I cant get my webcam output saved to a file. Here is what I have. This runs fine, launches the webcam and creates "output.avi" The issue is output.avi is tiny(414 bytes) and the same exact bytes each time I run the program. Im guessing the issue is with the fourcc encoding but I havent been able to find what works in my case. I am running on Mac OS X. Let me know if you need anymore information.

import numpy as np
import cv2

path = ('/full/path/Directory/output.avi')

cap = cv2.VideoCapture(0)
cap.set(1, 20.0) #Match fps
cap.set(3,640)   #Match width
cap.set(4,480)   #Match height

fourcc = cv2.cv.CV_FOURCC(*'XVID')
video_writer = cv2.VideoWriter(path,fourcc, 20.0, (640,480))

while(cap.isOpened()):
    #read the frame
    ret, frame = cap.read()
    if ret==True:
        #show the frame
        cv2.imshow('frame',frame)
        #Write the frame
        video_writer.write(frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
video_writer.release()
cv2.destroyAllWindows()

Answer

preezzzy picture preezzzy · Oct 19, 2014

Just need to change

fourcc = cv2.cv.CV_FOURCC(*'XVID')

to

fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')

Found answer here: opencv VideoWriter under OSX producing no output