Turn x numpy arrays with dimensions [n, m] into a single array with dimensions [x, n, m] in Python

Viewed 105

I am doing some image processing in Python. I have a set of grey scale images (512 x 512) saved in a stacked .tif file with 201 images. When I open this file with skimage.io.imread, it generates a 3D array with dimensions [201, 512, 512], allowing me to easily iterate over each greyscale image - which is what I desire.

After performing some operations on these images, I have a list of ten 2D arrays, which I want to put back into the same dimension format that skimage.io.imread produced - ie. [10, 512, 512].

Using numpy.dstack produces an array with dimension [512, 512, 10]. And numpy.concatenate does not do the job either.

How can I turn this list of 2D arrays into a 3D array with the dimensions specified above?

2 Answers

One solution is considering you have an array of shape [512, 512, 10] and move the last axis to the first:

import numpy as np
imgs = np.random.random((512, 512, 10))

imgs = np.moveaxis(imgs, -1, 0)
print(imgs.shape)
# (10, 512, 512)

The other ways is to use np.vstack() like:

import numpy as np

# List of 10 images of size (512 x 512) each
imgs = [np.random.random((512, 512)) for _ in range(10)]

output = np.vstack([x[None, ...] for x in imgs])
print(output.shape)
# (10, 512, 512)

The most general solution is to use plain np.stack and specify which axis you want to add to the array.

Taking the notation from @amrind's answer:

result = np.stack(imgs, axis=0)

This is roughly equivalent to just doing

result = np.array(imgs)
Related