Opencv 隔帧取数据解码速度优化

  • 实用tips,若使用opencv进行解码,代码作如下优化能极大提升解码速度:
复制代码
    cap = cv2.VideoCapture(file_path)
    videolen = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

    # 1. decode all frames, time cost!
    sampledFrames = []
    for i in range(videolen):
        ret, frame = cap.read()
        # maybe first frame is empty
        if ret == False:
            continue
        img = frame[:, :, ::-1]
        sampledFrames.append(img)

    cap.release()

    # 2. get frame index
    frames_idx = [xxx]

    # 3. sample
    frames = np.array(sampledFrames)
    imgs = []
    for idx in frames_idx:
        imgbuf = frames[idx]
        img = Image.fromarray(imgbuf, mode='RGB')
        imgs.append(img)

优化后:

复制代码
    cap = cv2.VideoCapture(file_path)
    videolen = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

    # 1. get frame index
    frames_idx = [xxx]

    # 2. decode target frame
    imgs = []
    for i in range(videolen):
        ret = cap.grab()
        # maybe first frame is empty
        if ret == False:
            continue  
        if frames_idx and i == frames_idx[0]:
            frames_idx.pop(0)
            ret, frame = cap.retrieve()
            if frame is None:
                break
            imgbuf = frame[:, :, ::-1]
            img = Image.fromarray(imgbuf, mode='RGB')
            imgs.append(img)
        if frames_idx == None:
            break
    cap.release()
相关推荐
亲持红叶几秒前
GLU 变种:ReGLU 、 GEGLU 、 SwiGLU
人工智能·深度学习·神经网络·激活函数
说私域1 分钟前
线上协同办公时代:以开源AI大模型等工具培养网感,拥抱职业变革
人工智能·开源
群联云防护小杜3 分钟前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
摘星编程8 分钟前
构建智能客服Agent:从需求分析到生产部署
人工智能·需求分析·智能客服·agent开发·生产部署
不爱学习的YY酱11 分钟前
信息检索革命:Perplexica+cpolar打造你的专属智能搜索中枢
人工智能
whaosoft-1431 小时前
51c自动驾驶~合集7
人工智能
刘晓倩4 小时前
Coze智能体开发实战-多Agent综合实战
人工智能·coze
石迹耿千秋5 小时前
迁移学习--基于torchvision中VGG16模型的实战
人工智能·pytorch·机器学习·迁移学习
路人蛃8 小时前
通过国内扣子(Coze)搭建智能体并接入discord机器人
人工智能·python·ubuntu·ai·aigc·个人开发
CV-杨帆9 小时前
论文阅读:arxiv 2025 A Survey of Large Language Model Agents for Question Answering
论文阅读·人工智能·语言模型