I often have to add 2d numpy (tiff images) arrays. To do this, I will first add them to the list and use np.dstack. This is apparently the fastest way to get 3D arrays stacking images. But is there a faster / more memory efficient way?
from time import time
import numpy as np
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)
print time()-t0
print stacked.shape
t0 = time()
temp = img[:,:,0]
for n in range(1, 100):
temp = np.dstack((temp, img[:,:,n]))
print time()-t0
print temp.shape
stacked = np.empty((256, 512, 100))
t0 = time()
for n in range(100):
stacked[:,:,n] = img[:,:,n]
print time()-t0
print stacked.shape
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
print stacked.shape
source
share