opencv - 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 安装,但没有运气。我不知道我缺少什么(或者我安装了什么,导致上述问题)。
任何建议,响应表示赞赏。谢谢。
解决方案
我正在尝试使用 Python 中的 Opencv 写入 .mp4 文件(4K)。
我想强调两点
-
- 正确初始化
fourcc
参数
-
fourcc = cv2.VideoWriter_fourcc("mp4v")
- 正确初始化
-
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()
推荐阅读
- ruby - batch file - running an installer that appends to the PATH and the running that new application from the bat
- javascript - 如何使用javascript修剪单词之间和逗号后的空格
- e2e-testing - 为什么我无法在 Chrome (cypress) 中以新问题形式显示可用的里程碑?
- azure - 保护 Azure 云服务配置中的敏感信息
- javascript - 这个代码片段是如何执行闭包的?
- java - java httpSession在处理时无效
- javascript - 如何在 React 中实现 FormValidation?
- android - 出现错误无法加载类 java.lang.NoClassDefFoundError:
- python - python将元素添加到数据框行
- javascript - 如何总结嵌套 Javascript 对象数组的所有叶节点?