0

我正在使用 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 中。

4

1 回答 1

1

您正在重新创建VideoWriterat 每个帧,最终只存储一个帧。您需要先创建编写器,在循环中将帧写入它,然后在完成视频后终止它。作为预防措施,如果我们在您阅读一帧时检测到视频中的任何问题,您还需要跳出循环。为确保您正确执行此操作,让我们在第一帧中读取,VideoWriter一旦我们建立了它的创建,就设置 then only write to it:

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()  
于 2020-10-26T19:49:58.620 回答