gpt4 book ai didi

python - Python + OpenCV + Base64:将框架转换为base64的问题

转载 作者:行者123 更新时间:2023-12-02 17:58:10 25 4
gpt4 key购买 nike

我正在尝试将视频转换为帧,并将那些帧转换为base64字符串。我无法这样做,并且遇到一些异常(exception)。下面是我的代码:

import cv2
import base64


def footage_to_frame(video):
vidcap = cv2.VideoCapture(video)
success, frames = vidcap.read()
if success:
return frames


def frame_to_base64(frames):
with frames as frame:
frame_b64 = base64.b64encode(frame.read())
return frame_b64
该方法的函数调用为:
frames = converter.footage_to_frame("/Users/myname/Desktop/video.mp4")
converter.frame_to_base64(frames)
以下是我在控制台中遇到的错误:
File "/Users/myname/Desktop/Test/src/service/converter.py", line 13, in frame_to_base64
with frames as frame:
AttributeError: __enter__

最佳答案

在函数frame_to_base64(frames)中,帧已经是单个图像,因为VideoCapture.read返回单个图像。这也是一个opencv镜像(numpy数组),您不能在其中使用“with”。

def frame_to_base64(frame):
return base64.b64encode(frame)
如果要阅读视频的所有帧,则应执行以下操作:
import cv2
import base64


def footage_to_frame(video):
vidcap = cv2.VideoCapture(video)
frames = []

# read until no more frames exist in the video
while True:
success, frame = vidcap.read()
if (success):
frames.append(frame)
else:
# unable to read a frame
break

return frames


def frames_to_base64(frames):
frames_b64 = []
# iterate frames and convert each of them to base64
for frame in frames:
frames_b64.append(base64.b64encode(frame))
return frames_b64
尽管取决于视频时长,您可能会遇到内存问题。

关于python - Python + OpenCV + Base64:将框架转换为base64的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64245597/

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