首页 > 解决方案 > VideoCapture obj 未在 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 安装,但没有运气。我不知道我缺少什么(或者我安装了什么,导致上述问题)。

任何建议,响应表示赞赏。谢谢。

标签: opencvopencv-python

解决方案


我正在尝试使用 Python 中的 Opencv 写入 .mp4 文件(4K)。

我想强调两点

    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()

推荐阅读