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()
相关推荐
IT_陈寒4 小时前
Vite打包时踩的坑:静态资源为啥突然404了?
前端·人工智能·后端
一点一木5 小时前
🚀 2026 年 6 月 GitHub 十大热门项目排行榜 🔥
人工智能·github
aneasystone本尊5 小时前
学习 turbovec 的 SIMD 搜索内核
人工智能
阳光是sunny14 小时前
别再被 worktree 绕晕了!AI 编程时代你必须掌握的 Git 隔离神器
前端·人工智能·后端
冬奇Lab14 小时前
每日一个开源项目(第148篇):obsidian-skills - Obsidian CEO 亲写的 AI Agent 格式规范,让 Agent 不再破坏你的 Vault
人工智能·开源·资讯
ethantan14 小时前
AI Agent 组成:像人一样思考的智能体
人工智能·程序员·架构
冬奇Lab14 小时前
Workflow 系列(05):评测体系——三层测试结构与 Trace 追踪
人工智能·工作流引擎
ethantan15 小时前
一篇讲解AI Agent 组成:像人一样思考的智能体
人工智能·后端·程序员
Cosolar17 小时前
vLLM 生产级部署完全指南
人工智能·后端·架构
CodePlayer竟然被占用了17 小时前
被美国政府封杀18天,Claude Fable 5 回来了——但代价是什么?
人工智能