簡體   English   中英

使用 fourcc 編解碼器 h264 和 h265 使用 opencv 從幀中保存視頻

[英]Saving video from frames in with fourcc codec h264 and h265 with opencv

我正在將實時 stream 中的幀保存到帶有 h264 編解碼器的視頻中。 我在 python 中嘗試使用 openCV(版本 3.4 和 4.4)進行此操作,但我無法保存它。 我可以將視頻保存在 XVID 和許多其他編解碼器中,但我在 h264 和 h265 中不成功。

我在 Python 中使用 windows opencv 4.4。

我的示例代碼如下

cap = cv2.VideoCapture(0)

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

        width  = int(cap.get(3)) # float
        height = int(cap.get(4)) # float
        # fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
        
        fourcc = cv2.VideoWriter_fourcc(*'H264')
        out = cv2.VideoWriter(filename, fourcc, 30, (width,height)) 
        out.write(frame)
out.release()  

誰能幫助我如何以 h264 和 h265 格式保存視頻。

您在每一幀重新創建VideoWriter ,最終只存儲一個幀。 您需要先創建編寫器,在循環中將幀寫入其中,然后在完成視頻后終止它。 作為預防措施,如果我們在您讀取幀時檢測到視頻中有任何問題,您還需要跳出循環。 為了確保你這樣做是正確的,讓我們在第一幀中讀取,設置VideoWriter然后只在我們建立它的創建后寫入它:

cap = cv2.VideoCapture(0)
out = None

while cap.isOpened():
    ret, frame = cap.read()
    if ret == True:
        if out is None:
            width  = int(cap.get(3)) # float
            height = int(cap.get(4)) # float

            fourcc = cv2.VideoWriter_fourcc(*'H264')
            out = cv2.VideoWriter(filename, fourcc, 30, (width, height))
        else:
            out.write(frame)
    else:
        break

if out is not None:
    out.release()  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM