【发布时间】:2014-06-18 11:22:17
【问题描述】:
我经常需要堆叠 2d numpy 数组(tiff 图像)。为此,我首先将它们附加到一个列表中并使用 np.dstack。这似乎是获得 3D 阵列堆叠图像的最快方法。但是,有没有更快/内存效率更高的方法?
from time import time
import numpy as np
# Create 100 images of the same dimention 256x512 (8-bit).
# In reality, each image comes from a different file
img = np.random.randint(0,255,(256, 512, 100))
t0 = time()
temp = []
for n in range(100):
temp.append(img[:,:,n])
stacked = np.dstack(temp)
#stacked = np.array(temp) # much slower 3.5 s for 100
print time()-t0 # 0.58 s for 100 frames
print stacked.shape
# dstack in each loop is slower
t0 = time()
temp = img[:,:,0]
for n in range(1, 100):
temp = np.dstack((temp, img[:,:,n]))
print time()-t0 # 3.13 s for 100 frames
print temp.shape
# counter-intuitive but preallocation is slightly slower
stacked = np.empty((256, 512, 100))
t0 = time()
for n in range(100):
stacked[:,:,n] = img[:,:,n]
print time()-t0 # 0.651 s for 100 frames
print stacked.shape
# (Edit) As in the accepted answer, re-arranging axis to mainly use
# the first axis to access data improved the speed significantly.
img = np.random.randint(0,255,(100, 256, 512))
stacked = np.empty((100, 256, 512))
t0 = time()
for n in range(100):
stacked[n,:,:] = img[n,:,:]
print time()-t0 # 0.08 s for 100 frames
print stacked.shape
【问题讨论】:
-
你可以避免调用
dstack,只要保证temp中的所有数组满足这个条件,你就可以简单地调用stacked = np.concatenate(temp,axis=2),这样可以节省少量的python开销时间。如果您显示更多代码,可能会有更好的方法来做到这一点,但如图所示,顶部代码几乎是最佳的。 -
temp 中的数组都是 2D 的,我想连接起来得到一个 3D 数组。因此,np.concatenate(temp, axis=2) 将产生错误:axis 2 out of bounds [0, 2)。 np.concatenate(temp, axis=1) 将创建一个二维数组 (256x51200)。
-
我错过了我评论的关键部分,它应该是“...如果满足此条件,
temp中的所有数组都是 3D ......”。应该注意的是,这种节省是微不足道的,除了非常大的临时尺寸,可能在每个阵列约 2us 的数量级上。