首页 > 解决方案 > 在 opencv 中使用 video.write 从图像创建 mp4 文件

问题描述

我正在尝试通过 opencv 在 python 中创建和保存视频文件

video_name = os.path.join(DIR, "test.mp4")
images = [img for img in os.listdir(DIR) if img.startswith(f'{test_')]
images = sorted(images, key=graph_utils_py.numericalSort)
frame = cv2.imread(os.path.join(DIR, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width, height))
for image in images:
    fpath = os.path.join(DIR, image)
    video.write(cv2.imread(fpath))
    os.remove(fpath)  # remove the image file
cv2.destroyAllWindows()
video.release()

以上生成的视频文件没有任何问题,但我收到警告

OpenCV: FFMPEG: tag 0x00000000/'????' is not supported with codec id 13 and format 'mp4 / MP4 (MPEG-4 Part 14)'
[mp4 @ 000001d0378cdec0] Could not find tag for codec rawvideo in stream #0, codec not currently supported in container

当我尝试将此视频文件嵌入使用乳胶生成的 pdf 时,这会产生问题。据我了解[The video data inside the file must be encoded with the H.264 codec.][1],成功查看 pdf 中的嵌入视频。

任何关于如何在 python 中使用 H.264 编解码器生成 mp4 文件的建议将不胜感激。

编辑:

我尝试了下面的建议,并出现以下错误

OpenCV: FFMPEG: tag 0x31435641/'AVC1' is not supported with codec id 27 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x31637661/'avc1'

Failed to load OpenH264 library: openh264-1.8.0-win64.dll
    Please check environment and/or download library: https://github.com/cisco/openh264/releases

[libopenh264 @ 000002833670e500] Incorrect library version loaded
Could not open codec 'libopenh264': Unspecified error

标签: python-3.ximageopencvvideopdflatex

解决方案


您需要通过正确的编解码器:

fourcc = cv2.VideoWriter_fourcc(*'AVC1')
fps = 1
video = cv2.VideoWriter(video_name, fourcc, fps, (width, height))

推荐阅读