I want to capture video from a webcam and save it to an mp4 file using opencv. I found example code on stackoverflow (below) that works great. The only hitch is that I'm trying to save it as mp4, not avi. Part of what I don't get is that the 'XVID' argument passed to the FOURCC writer is supposed to be, I think, an mp4 codec (from this link). If I change the filename to 'output.mp4' it tells me that the tag is invalid, so I have to believe that the XVID codec is actually making an avi file. Is this a stupid question? How do I write to an mp4?
I have found links showing how to convert an avi to an mp4 after the fact but that seems inefficient. Seems like I should be able to do it during the initial write.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
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):
Note: I installed openh264 as suggested by @10SecTom but I'm not sure if that was relevant to the problem.
Just in case:
The problem such as
OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id 13 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to use tag 0x00000020/' ???'
maybe that your output video size is not the same as original video. You can look over the frame size of video first.For someone whoe still struggle with the problem. According this article I used this sample and it works for me:
So I had to use
cv2.VideoWriter_fourcc(*'X264')
codec. Tested with OpenCV 3.4.3 compiled from sources.This is the default code given to save a video captured by camera
For about two minutes of a clip captured that
FULL HD
Using
The file saved was more than
150MB
Then had to use
ffmpeg
to reduce the size of the file saved, between30MB
to60MB
based on the quality of the video that is required changed usingcrf
lower the crf better the quality of the video and larger the file size generated. You can also change the formatavi
,mp4
,mkv
,etcThen i found ffmpeg-python
Here a code to save
numpy array
of each frame as video usingffmpeg-python
This worked for me.
There are some things to change in your code:
0x7634706d
:out = cv2.VideoWriter('output.mp4',0x7634706d , 20.0, (640,480))