如何用H264编解码器编写mp4视频文件?

时间:2017-05-12 14:45:09

标签: python opencv video ffmpeg codec

在OSX上我可以从我的网络摄像头录制并使用以下简单脚本编写视频文件:

import cv2
camera = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object to save the video
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video_writer = cv2.VideoWriter('output.avi', fourcc, 25.0, (640, 480))

while True:
    try:
        (grabbed, frame) = camera.read()  # grab the current frame
        frame = cv2.resize(frame, (640, 480))  # resize the frame
        video_writer.write(frame)  # Write the video to the file system

    except KeyboardInterrupt:
        camera.release()
        break

结果avi文件虽然很大。我想要一个较小的文件,最好是mp4。所以我将文件名更改为output.mp4,将fourcc编解码器更改为H264。这写了一个有效的视频文件,但给了我以下错误:

$ python write_video_file.py 
OpenCV: FFMPEG: tag 0x34363248/'H264' is not supported with codec id 28 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x00000021/'!???'

由于我认为我错过了ffmpeg中的H264编解码器,我决定卸载ffmpeg和opencv,并在H264支持下重新安装它们。为此我使用了以下命令:

# First ffmpeg
brew install ffmpeg --with-fdk-aac --with-libvidstab --with-openh264 \
      --with-openjpeg  --with-openssl --with-tools --with-webp --with-x265 --with-zeromq
# then opencv3
brew tap homebrew/science
brew install opencv3 --with-contrib --with-ffmpeg --with-tbb

在此之后,我使用以下组合再次运行脚本:

  • output.mp4H264
  • output.mp4X264

不幸的是,我仍然收到OpenCV警告/错误。该文件是可读的,但我仍然惹恼我,我得到这些错误。有没有人知道如何使用H264编解码器制作OpenCV写入mp4视频文件?

欢迎所有提示!

1 个答案:

答案 0 :(得分:1)

我花了很多时间试图在 macOS 上找到视频编解码器列表,找到哪些编解码器可以使用哪些容器,然后 QuickTime 实际上可以读取生成的文件

我可以总结一下我的发现如下:

.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

我确实设法在h264容器中编写mp4视频,只是不使用OpenCV的 VideoWriter 模块。相反,我改变了代码(我的C ++)只输出原始bgr24格式数据 - 这就是OpenCV喜欢存储像素的方式:

因此,存储在名为Mat的{​​{1}}中的视频帧的输出变为:

Frame

然后将程序的输出管道输入cout.write(reinterpret_cast<const char *>(Frame.data),width*height*3); ,如下所示:

ffmpeg

是的,我知道我做了一些假设:

  • 数据为CV8_UC3,
  • 尺寸匹配 OpenCV ffmpeg
  • OpenCV 数据中没有填充或疯狂的步幅,

但基本技术有效,您可以根据其他尺寸和情况进行调整。