簡體   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