Ril*_*y K 3 python opencv save video-processing
在开始修改视频中的帧之前,我试图获得一个复制视频的非常简单的示例。但是,与 2.8 mb Barriers.avi 视频相比,output.avi 视频是一个 5kb 的损坏文件。我使用的是 OpenCV 版本 4.2.0 和 Python 版本 3.7.7。
这是代码:
import cv2
input = cv2.VideoCapture("../video/barriers.avi")
height = int(input.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(input.get(cv2.CAP_PROP_FRAME_WIDTH))
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter('../video/output5.avi', fourcc, 30, (height, width), isColor=True)
while input.isOpened():
# get validity boolean and current frame
ret, frame = input.read()
# if valid tag is false, loop back to start
if not ret:
break
else:
out.write(frame)
input.release()
out.release()
Run Code Online (Sandbox Code Playgroud)
如果我打印框架形状,我会得到:
(480, 640, 3)
Run Code Online (Sandbox Code Playgroud)
注意:其他堆栈溢出解决方案都没有帮助。
编辑:如果使用 cv2.imshow(),所有帧都显示良好。
我想解决您的代码中的两个问题:
问题#1::您想要创建一个.avi视频文件。因此,您需要将 fourcc 初始化为MJPG:
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
Run Code Online (Sandbox Code Playgroud)
创建视频文件有某些组合。例如,如果您想创建一个,.mp4请将 fourcc 初始化为*'mp4v'。
问题#2:确保输出视频的大小与输入帧的大小相同。例如:您声明了 Videowriter 对象 size(height, width)。那么你的框架必须具有相同的尺寸:
frame = cv2.resize(frame, (height, width))
Run Code Online (Sandbox Code Playgroud)
代码:
import cv2
cap = cv2.VideoCapture("output.mp4")
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('output5.avi', fourcc, 30, (width, height), isColor=True)
while cap.isOpened():
# get validity boolean and current frame
ret, frame = cap.read()
# if valid tag is false, loop back to start
if not ret:
break
else:
frame = cv2.resize(frame, (width, height))
out.write(frame)
cap.release()
out.release()
Run Code Online (Sandbox Code Playgroud)