How to write mp4 video file with H264 codec?

后端 未结 1 1037
慢半拍i
慢半拍i 2021-01-27 03:44

On OSX I can record from my webcam and write a video file with the following simple script:

import cv2
camera = cv2.VideoCapture(0)

# Define the codec and creat         


        
相关标签:
1条回答
  • 2021-01-27 03:48

    I spent ages trying to find a list of video codecs on macOS, and finding which codecs work with which containers, and then if QuickTime can actually read the resulting files.

    I can summarise my findings as follows:

    .mov container and fourcc('m','p','4','v') work and QuickTime can read it
    .mov container and fourcc('a','v','c','1') work and QuickTime can read it
    .avi container and fourcc('F','M','P','4') works but QuickTime cannot read it without conversion
    

    I did manage to write h264 video in an mp4 container, as you wanted, just not using OpenCV's VideoWriter module. Instead I changed the code (mine happens to be C++) to just output raw bgr24 format data - which is how OpenCV likes to store pixels anyway:

    So the output of a frame of video stored in a Mat called Frame becomes:

    cout.write(reinterpret_cast<const char *>(Frame.data),width*height*3);
    

    and then you pipe the output of your program into ffmpeg like this:

    ./yourProgram | ffmpeg -y -f rawvideo -pixel_format bgr24 -video_size 1024x768 -i - -c:v h264 -pix_fmt yuv420p video.mp4
    

    Yes, I know I have made some assumptions:

    • that the data are CV8_UC3,
    • that the sizes match in OpenCV and ffmpeg, and
    • that there is no padding or mad stride in the OpenCV data,

    but the basic technique works and you can adapt it for other sizes and situations.

    0 讨论(0)
提交回复
热议问题