简体   繁体   English

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

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

I am saving frames from live stream to a video with h264 codec.我正在将实时 stream 中的帧保存到带有 h264 编解码器的视频中。 I tried this with openCV (versions 3.4 and 4.4) in python but I am not able to save it.我在 python 中尝试使用 openCV(版本 3.4 和 4.4)进行此操作,但我无法保存它。 I can save video in XVID and many other codecs but I am not successful in h264 and h265.我可以将视频保存在 XVID 和许多其他编解码器中,但我在 h264 和 h265 中不成功。

I am using windows opencv 4.4 in Python.我在 Python 中使用 windows opencv 4.4。

My sample code is as follow我的示例代码如下

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()  

Can anyone help me how can I save video in h264 and h265.谁能帮助我如何以 h264 和 h265 格式保存视频。

You are recreating the VideoWriter at each frame which in the end only stores a single frame.您在每一帧重新创建VideoWriter ,最终只存储一个帧。 You need to create the writer first, write the frames to it in the loop then terminate it after you're finished with the video.您需要先创建编写器,在循环中将帧写入其中,然后在完成视频后终止它。 As a precaution you'll also want to break out of the loop if we detect any problems in the video when you read a frame.作为预防措施,如果我们在您读取帧时检测到视频中有任何问题,您还需要跳出循环。 To make sure you do this right, let's read in the first frame, set up the VideoWriter then only write to it once we've established its creation:为了确保你这样做是正确的,让我们在第一帧中读取,设置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