我有一个文件夹,比如说video1
一堆按顺序排列的图像frame_00.png, frame_01.png, ...
我想要的是格式为 4D numpy 数组(number of frames, w, h, 3)
这就是我所做的,但我认为它很慢,有没有更快或更有效的方法来实现同样的事情?
folder = "video1/"
import os
images = sorted(os.listdir(folder)) #["frame_00", "frame_01", "frame_02", ...]
from PIL import Image
import numpy as np
video_array = []
for image in images:
im = Image.open(folder + image)
video_array.append(np.asarray(im)) #.transpose(1, 0, 2))
video_array = np.array(video_array)
print(video_array.shape)
#(75, 50, 100, 3)
有一个较旧的 SO 线程 https://stackoverflow.com/q/44078327/425458关于这个主题,有很多细节(甚至可能有点太多)。我不会投票结束这个问题,我将快速概述该线程的主要要点:
- 最快的常用图像读取功能是
imread
来自cv2
包裹。
- 读取图像然后将它们添加到普通的 Python 列表中(正如您已经在做的那样)是读取大量图像的最快方法。
- However, given that you are eventually converting the list of images to an array of images, every possible method of building up an array of images is almost exactly as fast as any other
- 有趣的是,如果您采用将图像直接分配给预分配数组的方法,则实际上分配给哪些索引(即哪个维度)对于获得最佳性能很重要。
所以基本上,在纯单线程 Python 中工作时,你将无法获得更快的速度。您可能会因切换到cv2.imread
(代替PIL.Image.open
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)