【问题标题】:OpenCV MP4 CreationOpenCV MP4 创建
【发布时间】:2016-12-12 19:05:56
【问题描述】:

我一直在尝试在 python 中使用 OpenCV 编写 MP4 视频文件。

当我同时使用 linux 和 windows 时,AVI 创建工作正常:

out = cv2.VideoWriter('x.avi', 0, 30, (640, 480))

fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter('x.avi', fourcc, 30, (640, 480))

甚至

fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter('x', fourcc, 30, (640, 480))

.

当我尝试保存 MP4 但没有保存时​​ - 使用:

fourcc = cv2.VideoWriter_fourcc(*"H264")
out = cv2.VideoWriter('x.mp4', fourcc, 30, (640, 480))

fourcc = cv2.VideoWriter_fourcc(*"AVC1")
out = cv2.VideoWriter('x.mp4', fourcc, 30, (640, 480))

没有错误发生,只是没有保存。

过去几天我尝试了所有方法,尽一切努力避免创建 AVI,然后使用 ffmpeg 将其转换为 MP4,因为我发现这是一种可怕的做法。

【问题讨论】:

  • 我猜opencv在videowriter中使用ffmpeg对视频进行编码(转码)和打包。也许你的系统上没有它?作为一种解决方法,您可以使用 ffmpeg 将您的 avi 转换为 mp4。
  • 如果我安装了 FFMPEG,你认为它会起作用吗?
  • 是python模块还是实际的windows程序什么的
  • cv::VideoWriter::VideoWriter 上的文档说:构造函数/函数初始化视频编写器。在 Linux 上 FFMPEG 用于编写视频;在 Windows 上使用 FFMPEG 或 VFW;在 MacOSX 上使用 QTKit。 我不认为 openCV 自己实现了 H.264 编码器和 ISOBMFF。
  • 我也有同样的问题。有时我得到一个视频,有时我得到一个空文件。你解决问题了吗?

标签: python opencv video ffmpeg


【解决方案1】:

为框架的高度和宽度提供正确的值:

import cv2

print ('Press [ESC] to quit demo')
# Read from the input video file
# input_file = 'Your path to input video file'
# camera = cv2.VideoCapture(input_file)

# Or read from your computer camera
camera = cv2.VideoCapture(0)

# Output video file may be with another extension, but I didn't try
# output_file = 'Your path to output video file' + '.avi'
output_file = "out.avi"

# 4-byte code of the video codec may be another, but I did not try
fourcc = cv2.VideoWriter_fourcc(*'DIVX')

is_begin = True
while camera.isOpened():
    _, frame = camera.read()
    if frame is None:
        break

    # Your code
    processed = frame

    if is_begin:
        # Right values of high and width
        h, w, _ = processed.shape
        out = cv2.VideoWriter(output_file, fourcc, 30, (w, h), True)
        print(out.isOpened()) # To check that you opened VideoWriter
        is_begin = False

    out.write(processed)
    cv2.imshow('', processed)
    choice = cv2.waitKey(1)
    if choice == 27:
        break

camera.release()
out.release()
cv2.destroyAllWindows()

此代码对我有用。

【讨论】:

  • 这是 .avi 视频的基本示例,而不是要求的 mp4
  • 提供正确的宽度和高度值为我解决了类似的问题。我有 1920x1080 帧,并且错误地指定了 640x480(希望在保存时这些帧会被截断)。相反,mp4 文件只包含一个小标题(约 200 字节)。一旦我正确指定了尺寸,视频就会正确保存。
猜你喜欢
  • 2017-05-06
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多