VideoCapture 对象未读取 python (Ubuntu 20.04)

VideoCapture obj not reading in python (Ubuntu 20.04)

我正在尝试在 Python 中使用 Opencv 写入 .mp4 文件 (4K)。 (Ubuntu 20.04)
下面是我一直在处理的代码:

cap = VideoCapture(video_path)
is_opened = cap.isOpened() # returns True
width, height = int(cap.get(3)), int(cap.get(4)) # returns correct values
ret, frame = cap.read() # returns False, None respectively

视频打开,但 cap.read() 无法运行。我已经尝试过其他类型的视频,它确实有效。也许是特定的编解码器? (4K + mp4) 不工作。

此外,我有三个系统 运行 Ubuntu 20.04 安装了不同的软件包。 上述症状不仅仅出现在一个系统上。我尝试尽可能多地同步 Python 安装,但没有成功。我不知道我缺少了什么(或者我安装了什么,导致了上述问题)。

如有任何建议,我们将不胜感激。 谢谢

I'm trying to write to a .mp4 file (4K) with Opencv in Python.

我想强调两点

    1. 正在正确初始化 fourcc 参数
    • fourcc = cv2.VideoWriter_fourcc("mp4v")
      
    1. 正在正确初始化 VideoWriter
    • VideoWriter的宽高参数必须与当前帧一致

      • 如果您正在读取输入视频,您可以获得像这样的宽度和高度:

        • _, example_frame = cap.read()
          (h, w) = example_frame.shape[:2]
          
        • 但是如果您打算调整框架的大小,请将宽度和高度设置为新的大小

    • 如果你处理的是彩色图像?如果是这样,您应该将 isColor 设置为 True,否则设置为 False。

    • output = "output.mp4"
      fps = 24
      writer = cv2.VideoWriter(output, fourcc,
                               (w, h), isColor=True)
      

这是一个示例代码:


import cv2

cap = cv2.VideoCapture("input.mp4")
_, example_frame = cap.read()
(h, w) = example_frame.shape[:2]
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
fps = 24
output = "output.mp4"
writer = cv2.VideoWriter(output, fourcc, fps, (w, h), isColor=True)

while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        writer.write(frame)
        cv2.imshow("frame", frame)
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break

cap.release()
writer.release()