使用opencv

问题描述

我正在使用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()  

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...