You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将all_frames列表转为numpy数组以适配imageio写入视频?

解决方法:将PIL Image列表转换为Numpy数组适配imageio写入

你的all_frames列表中存储的是PIL Image对象,而imageio.mimwrite对Numpy数组的兼容性更好。你可以通过两种方式完成转换:

方式1:在收集帧时直接存储Numpy数组

修改代码中添加帧的逻辑,将PIL Image转为Numpy数组后再加入列表:

all_frames = []

for j, image in enumerate(image_batch): 
    image_index = (i * batch_size) + j
    if not self.use_tf:
        image = (image.permute(1, 2, 0) * 127.5 + 128).clamp(0, 255).to(torch.uint8).squeeze(0)
    array = np.array(image)

    for effect in self.custom_effects:
        array = effect.apply_effect(array = array, 
                                    index = image_index)

    final_image = Image.fromarray(array, 'RGB')

    if resolution:
        final_image = final_image.resize((resolution, resolution))

    # 替换原append逻辑,直接存Numpy数组
    all_frames.append(np.array(final_image))

# 直接写入Numpy数组列表
imageio.mimwrite('tmp.mp4', all_frames, quality=8, fps=self.sr/self.frame_duration)

方式2:在写入前统一转换列表为4维Numpy数组

如果不想修改收集逻辑,可以在调用mimwrite前,将整个列表转换为一个形状为(帧数, 高度, 宽度, 3)的4维Numpy数组:

# 在原代码收集完all_frames后添加:
frames_array = np.stack([np.array(frame) for frame in all_frames], axis=0)

# 写入转换后的数组
imageio.mimwrite('tmp.mp4', frames_array, quality=8, fps=self.sr/self.frame_duration)

注意事项

  • 确保所有帧的尺寸(宽高)一致,否则np.stack会报错(你的代码中已经通过resize保证了这一点,没问题)
  • 转换后的数组dtype应为uint8(对应0-255的像素值),原代码中处理后的图像已经符合这个要求

内容的提问来源于stack exchange,提问作者Atakan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:36:29