如何使用生成器并行读取视频?

问题描述

一般来说,我对多重处理了解不多。

我有以下代码可以根据给定的视频生成一系列帧:

def read_video(filename: str) -> np.array:
    w,h = get_resolution(filename)

    command = [
        "ffmpeg","-i",filename,"-f","image2pipe","-pix_fmt","bgr24","-vsync","0","-vcodec","rawvideo","-",]

    pipe = sp.Popen(command,stdout=sp.PIPE,bufsize=-1)
    while True:
        data = pipe.stdout.read(w * h * 3)
        if not data:
            break
        yield np.frombuffer(data,dtype="uint8").reshape((3,h,w))

然后有一个函数,稍后使用Pytorch模型和上面定义的生成器对视频帧进行推断,而我想在这里使用视频帧填充批处理,然后调用该模型一次以获取整个批处理的预测利用gpu的力量:

def inference_step(img_generator: Iterable,model: nn.Module,batch_size: int) -> None:
    inputs = [] 
    for i,img in enumerate(img_generator):
        if len(inputs) < batch_size:
            inputs.append(torch.from_numpy(img)) 
            # append is slow so one can use inputs[i % batch_size]
            continue
        outputs = model(inputs)
        inputs = []
        ...

所以,我的问题是如何修改代码,以使其并行加载框架,但同时保留其顺序?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)