使用fourcc编解码器h264和opencv中的h265从帧中保存视频

2024-04-29 22:52:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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中保存视频吗


Tags: get视频编解码器floatoutwidthcv2frame
1条回答
网友
1楼 · 发布于 2024-04-29 22:52:28

您正在每个帧上重新创建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()  

相关问题 更多 >