user785099 user785099 - 1 month ago 5
Python Question

add a dummy dimension for a multi-dimensional array

There has a nd array

A
with shape
[100,255,255,3]
, which correspond to 100 255*255 images. I would like to iterate this multi-dimensional array, and each iteration I get one image. This is what I do,
A1 = A[i,:,:,:]
The resulting
A1
has shape
[255,255,3]
. However, i would like to enforce it have the shape
[1,255,255,3]
. How can I do it?

SCB SCB
Answer

Use np.newaxis on your resulting array.

Very simple example on a 2d array:

x = np.array([[0, 1], [2, 3]])
x.shape
#: (2, 2)
x[np.newaxis]
#: array([[[0, 1],
#:         [2, 3]]])
x[np.newaxis].shape
#: (1, 2, 2)
Comments