gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:16:30 27 4
gpt4 key购买 nike

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

关于python - 使用opencv使用fourcc编解码器h264和h265从帧中保存视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64542380/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com