【问题标题】:Saving video from frames in with fourcc codec h264 and h265 with opencv使用fourcc编解码器h264和使用opencv的h265从帧中保存视频
【发布时间】:2021-02-09 00:29:06
【问题描述】:

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

【问题讨论】:

    标签: python opencv video h.264 openh264


    【解决方案1】:

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

    【讨论】:

    • 好的,这是一个错误。但主要问题是使用 h264 编写。即使只在循环外创建一次,它也无法使用编解码器 h264 和 h265 编写
    • 您使用的是哪个操作系统?
    • 我正在使用带有 opencv 4.4 的 windows 10
    • 您需要确保您使用的是 OpenH264,这是唯一与 OpenCV 兼容并在 Windows 中编写 H264 文件的框架:answers.opencv.org/question/103267/…
    • 亲,我用了你说的程序。我下载了 openh264.dll 文件并将其放在我的脚本所在的同一目录中,以及我在更改目录时保存文件的目录中。但它仍然没有保存视频。它用 0 个字节保存它。还有什么可做的吗?我错过了什么吗?
    猜你喜欢
    • 2022-01-11
    • 2019-01-02
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 2014-05-16
    相关资源
    最近更新 更多