87

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()
5
  • Try using -> fourcc = cv2.cv.CV_FOURCC(*'H264') Commented May 28, 2015 at 15:37
  • You will need ffmpeg though Commented May 28, 2015 at 15:37
  • 3
    Try with CV_FOURCC('m', 'p', '4', 'v'). Here is an example: stackoverflow.com/a/28904970/4481702 Commented May 28, 2015 at 15:48
  • @Ha Dang: Nope. That example does exactly the same thing that I'm seeing. The file is still saved as an avi. Commented May 28, 2015 at 17:49
  • 2
    Do you change the output filename to .mp4 extention or not? How do you know it's still saved as avi? Commented May 29, 2015 at 14:51

13 Answers 13

113

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))
Sign up to request clarification or add additional context in comments.

10 Comments

It's been two years! You hadn't expected this upvote, huh? :P I was using H264 to write to an mp4 file. It created laggy videos upon seeking, this suggestion helped me. MP4V codec solved the issue! :)
@varun ha no didnt see it coming :) .. glad it helped you bud.
It is not working, and says the below error: 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/' ???'
@BahramdunAdil the name of the output file must end with .mp4, that's why you are having that error
I had error codec id 12 instead of @BahramdunAdil 's 13 and changing the CODEC to *'mp4v' from to *'MP4V' fixed it for me.
|
27

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'):
        break

cap.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

1 Comment

openh264 has NO RELATION to "MP4V". MP4V is H.263, not H.264.
17

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))

1 Comment

0x7634706d is the same as mp4v (lowercase) using fourcc
12

This is the default code given to save a video captured by camera

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_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()

For about two minutes of a clip captured that FULL HD

Using

cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
cap.set(3,1920)
cap.set(4,1080)
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (1920,1080))

The file saved was more than 150MB

Then had to use ffmpeg to reduce the size of the file saved, between 30MB to 60MB based on the quality of the video that is required changed using crf lower the crf better the quality of the video and larger the file size generated. You can also change the format avi,mp4,mkv,etc

Then i found ffmpeg-python

Here a code to save numpy array of each frame as video using ffmpeg-python

import numpy as np
import cv2
import ffmpeg

def save_video(cap,saving_file_name,fps=33.0):

    while cap.isOpened():
        ret, frame = cap.read()
        if ret:
            i_width,i_height = frame.shape[1],frame.shape[0]
            break

    process = (
    ffmpeg
        .input('pipe:',format='rawvideo', pix_fmt='rgb24',s='{}x{}'.format(i_width,i_height))
        .output(saved_video_file_name,pix_fmt='yuv420p',vcodec='libx264',r=fps,crf=37)
        .overwrite_output()
        .run_async(pipe_stdin=True)
    )

    return process

if __name__=='__main__':

    cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
    cap.set(3,1920)
    cap.set(4,1080)
    saved_video_file_name = 'output.avi'
    process = save_video(cap,saved_video_file_name)

    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret==True:
            frame = cv2.flip(frame,0)
            process.stdin.write(
                cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                    .astype(np.uint8)
                    .tobytes()
                    )

            cv2.imshow('frame',frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                process.stdin.close()
                process.wait()
                cap.release()
                cv2.destroyAllWindows()
                break
        else:
            process.stdin.close()
            process.wait()
            cap.release()
            cv2.destroyAllWindows()
            break

1 Comment

'For about two minutes of a clip captured that FULL HD' where did you specify 2 minutes in the code?
6

fourcc = cv2.VideoWriter_fourcc(*'mp4v')

'mp4v' returns no errors unlike 'MP4V' which is defined inside fourcc

for the error:

"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/' ???'"

Comments

3

This worked for me, I added images.sort() to keep the sequence order:

import cv2
import numpy as np
import os

image_folder = 'data-set-race-01'
video_file = 'race-01.mp4'
image_size = (160, 120)
fps = 24

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
images.sort()

out = cv2.VideoWriter(video_file, cv2.VideoWriter_fourcc(*'MP4V'), fps, image_size)

img_array = []
for filename in images:
    img = cv2.imread(os.path.join(image_folder, filename))
    img_array.append(img)
    out.write(img)

out.release()

1 Comment

if the sequence number in the file name lacks leading zeros, then this can shuffle the sequence to become garbage. -- that isn't OP's problem. don't post answers to other questions here.
2

For someone whoe still struggle with the problem. According this article I used this sample and it works for me:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'X264')
out = cv2.VideoWriter('output.mp4',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()

So I had to use cv2.VideoWriter_fourcc(*'X264') codec. Tested with OpenCV 3.4.3 compiled from sources.

1 Comment

Instructions on how to compile opencv here swiftlane.com/eng/…
1

You need to set the codec to 'mp4v' (lowercase). If set in uppercase, an error would be thrown saying that is not supported, suggesting to use lowercase instead: OpenCV:FFMPEG:fallback to use tag 0x7634706d/'mp4v'. You may also want to have a look at the documentation of VideoWriter, as well as the examples given here. Also, please make sure your output video's size is equal to your input frame size (the below takes care of this, using the dimensions of the VideoCapture object).

cap = cv2.VideoCapture(0)
w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
fps = cap.get(cv2.CAP_PROP_FPS) 
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, fps, (int(w),int(h)))

You can get the entire list of codecs available for mp4, etc., by setting fourcc=-1. For instance:

out = cv2.VideoWriter('output.mp4', -1, fps, (int(w),int(h)))

1 Comment

It works!!! as of Sept 2024
1

The OpenCV documentation is not very rich with regard to the VideoWriter, however I managed to get it working in the following way (by looking at the stacktrace):

import cv2

HEIGHT = 480
WIDTH = 640
FPS = 30.0

cap = cv2.VideoCapture(0, cv2.CAP_ANY)

cap.set(cv2.CAP_PROP_FPS, FPS)
cap.set(cv2.CAP_PROP_CONVERT_RGB , 1)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 100)


cap.set(cv2.CAP_PROP_FRAME_WIDTH, WIDTH)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, HEIGHT)

fourcc = cv2.VideoWriter_fourcc(*'mp4v')

# output parameters such as fps and size can be changed
output = cv2.VideoWriter("output.mp4", fourcc, FPS, (WIDTH, HEIGHT))

while True:
    if cap.isOpened():
        (ret, frame) = cap.read()
        if ret:
            output.write(frame)
        cv2.imshow("frame", frame)

    if cv2.waitKey(10) == ord('q'):
        break

output.release()
cap.release()
cv2.destroyAllWindows()

The stacktrace error was:

OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id 12 and 
format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'

Unfortunately, it is difficult to find a list of the official codecs used by OpenCV, or at least I could not find them. In any case, it appears that you have to enter the codec 'mp4v' written in lower case.

https://docs.opencv.org/3.4/dd/d01/group__videoio__c.html#gac005718f121379beffdbdbfb44f2646a

One important thing I noticed is that the aspect ratio of the frame and the output video must be the same, which is why I use two variables for height and width. If these two are different, the file is created, but the frames are not saved (you always end up with a 1KB mp4 file). To avoid any problems you could do the same for FPS.

Comments

0

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.

3 Comments

No, that problem is because the video codec doesn't match with the output's filename. If u are using MP4V, the output file must end with .mp4. Same way with XVID output filename should end with .avi
I went down this deep dive and recorded my solution in this blog post if that helps swiftlane.com/eng/…
this error has NOTHING to do with frame sizes not matching VideoWriter's configured frame size. independent things.
-1

On Ubuntu 22.04 (2023) cv2.VideoWriter_fourcc(*'mp4v') worked for me.

Comments

-1

This works for me,

OS: Windows 11

Python: 3.12.0

OpenCV: 4.9.0.80

import cv2

vid_source_path = 0     # Path to video source, 0 for webcam
# vid_source_path = 'input_vi.mp4'     # Path to video source, 0 for webcam
cap = cv2.VideoCapture(vid_source_path)

if not cap.isOpened():
    print("Error: Could not open video Source.")
    exit()


# Define the codec and create VideoWriter object
ret = False
while not ret:
    ret, frame = cap.read()
    if not ret:
        print("Failed to grab the first frame from the video source, Trying again...")
    else:
        print(f'Height: {frame.shape[0]}, Width: {frame.shape[1]}')

height, width = frame.shape[:2]

# TO save the video in AVI format
# fourcc = cv2.VideoWriter_fourcc(*'XVID')  # You can change the codec if needed
# out = cv2.VideoWriter('output_vid.avi', fourcc, 20.0, (width, height))


# To save the video in MP4 format
# Note: 'X264' might not work on some systems, 'MP4V' or 'AVC1' can be alternatives.
fourcc = cv2.VideoWriter_fourcc(*'X264')
out = cv2.VideoWriter('output_vid.mp4', fourcc, 20.0, (width, height))



while (cap.isOpened()):
    ret, frame = cap.read()
    if ret != True:
        break

    # write the frame
    out.write(frame)

    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


cap.release()
out.release()
cv2.destroyAllWindows()

Comments

-2

just change the codec to "DIVX". This codec works with all formats.

fourcc = cv2.VideoWriter_fourcc(*'DIVX')

i hope this works for you!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.