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()
相关推荐
吴佳浩1 天前
LangChain 深入
人工智能·python·langchain
LplLpl111 天前
AI 算法竞赛通关指南:基于深度学习的图像分类模型优化实战
大数据·人工智能·机器学习
依米s1 天前
各年度人工智能大会WAIC核心议题(持续更新)
人工智能·人工智能+·waic·人工智能大会+
python机器学习建模1 天前
22篇经典金融风控论文复现(2025年11月更新)
人工智能·机器学习·论文·期刊·金融风控
Codebee1 天前
深度解析AI编程技术:从原理到实践,手把手教你落地
人工智能·设计模式·开源
武汉唯众智创1 天前
基于五级工的人工智能训练师教学解决方案
人工智能·ai·产教融合·人工智能训练师·五级工·ai训练师
执笔论英雄1 天前
【RL】python协程
java·网络·人工智能·python·设计模式
你好~每一天1 天前
未来3年,最值得拿下的5个AI证书!
数据结构·人工智能·算法·sqlite·hbase·散列表·模拟退火算法
老前端的功夫1 天前
前端技术选型的理性之道:构建可量化的ROI评估模型
前端·javascript·人工智能·ubuntu·前端框架
Mxsoft6191 天前
我发现区块链数据同步延迟,某次故障溯源卡顿,动态调整共识机制救场!
人工智能