Writing an mp4 video using python opencv Writing an mp4 video using python opencv python python

Writing an mp4 video using python opencv


This worked for me.

self._name = name + '.mp4'self._cap = VideoCapture(0)self._fourcc = VideoWriter_fourcc(*'MP4V')self._out = VideoWriter(self._name, self._fourcc, 20.0, (640,480))


There are some things to change in your code:

  1. Change the name of your output to 'output.mp4' (change to .mp4)
  2. I had the the same issues that people have in the comments, so I changed the fourcc to 0x7634706d: out = cv2.VideoWriter('output.mp4',0x7634706d , 20.0, (640,480))


What worked for me was to make sure the input 'frame' size is equal to output video's size (in this case, (680, 480) ).

http://answers.opencv.org/question/27902/how-to-record-video-using-opencv-and-python/

Here is my working code (Mac OSX Sierra 10.12.6):

cap = cv2.VideoCapture(0)cap.set(3,640)cap.set(4,480)fourcc = cv2.VideoWriter_fourcc(*'MP4V')out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (640,480))while(True):    ret, frame = cap.read()    out.write(frame)    cv2.imshow('frame', frame)    c = cv2.waitKey(1)    if c & 0xFF == ord('q'):        breakcap.release()out.release()cv2.destroyAllWindows()

Note: I installed openh264 as suggested by @10SecTom but I'm not sure if that was relevant to the problem.

Just in case:

brew install openh264