为了账号安全,请及时绑定邮箱和手机立即绑定

Python + OpenCV + Base64:将帧转换为 Base64 时出现问题

Python + OpenCV + Base64:将帧转换为 Base64 时出现问题

慕妹3146593 2023-10-18 21:12:38
我正在尝试将视频转换为帧,并将这些帧转换为 Base64 字符串。我无法这样做并得到一些例外。下面是我的代码:import cv2import base64def footage_to_frame(video):    vidcap = cv2.VideoCapture(video)    success, frames = vidcap.read()    if success:        return framesdef 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__
查看完整描述

1 回答

?
ITMISS

TA贡献1871条经验 获得超8个赞

在函数frame_to_base64(frames)中,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

尽管根据视频长度,您可能会遇到内存问题。


查看完整回答
反对 回复 2023-10-18
  • 1 回答
  • 0 关注
  • 68 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信