繁体   English   中英

如何使用 OpenCV 和 Python 录制和保存视频?

[英]How to record and save a video using OpenCV and Python?

我从这个网站上获取了以下代码。

import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'avc1')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        out.write(frame)
        cv2.imshow('Video', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

我面临的问题是视频正在存储,但我无法打开它。 视频大小约6KB,但时长为0秒。 我怎样才能解决这个问题?

我确实检查了与此类似的其他问题,但没有一个能解决我面临的问题。

如果我保存了错误大小的帧,我在打开文件时会遇到问题。

如果相机给出尺寸的框架,即。 (800, 600)那么你必须用相同的大小写(800, 600)或者你必须在保存之前使用 CV 将帧大小调整为(640, 480)

    frame = cv2.resize(frame, (640, 480))

完整代码

import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'avc1') #(*'MP42')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

while cap.isOpened():
    ret, frame = cap.read()
    if ret:

        frame = cv2.resize(frame, (640, 480))

        out.write(frame)
        cv2.imshow('Video', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

GitHub 上的示例: furas/python-examples/cv2/record-file

我在多次谷歌搜索后发现的一件事是 VideoWriter 默默地失败了。

就我而言,我没有 VideoCapture 对象,而是一个帧列表。 我遵循了与您所做的类似的指南,但问题是我根据img.shape[:2]给我的内容传递了数组的形状。 IIRC,OpenCV 的宽度和高度顺序与 numpy 数组不同,这是我问题的根源。 请参阅下面的评论从这里

正如@pstch 所述,在 Python 中创建 VideoWriter 时,应以 cv.VideoWriter(filename, Fourcc, fps, (w, h), ...) 形式传递帧尺寸。 当创建框架本身时 - 以相反的顺序: frame = np.zeros((h, w), ...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM