How can I add new dimensions to a Numpy array?

npreshape
numpy add dimension of zeros
numpy append
numpy concatenate
numpy newaxis
numpy repeat along new axis
np.expand_dims keras
numpy expand_dims axis=-1

I'm starting off with a numpy array of an image.

In[1]:img = cv2.imread('test.jpg')

The shape is what you might expect for a 640x480 RGB image.

In[2]:img.shape
Out[2]: (480, 640, 3)

However, this image that I have is a frame of a video, which is 100 frames long. Ideally, I would like to have a single array that contains all the data from this video such that img.shape returns (480, 640, 3, 100).

What is the best way to add the next frame -- that is, the next set of image data, another 480 x 640 x 3 array -- to my initial array?

You're asking how to add a dimension to a NumPy array, so that that dimension can then be grown to accommodate new data. A dimension can be added as follows:

image = image[..., np.newaxis]

numpy.expand_dims — NumPy v1.19 Manual, Expand the shape of an array. Insert a new axis that will appear at the axis position in the expanded array shape. Input array. Numpy is a great Python library for array manipulation. You can easily calculate mathematical calculation using the Numpy Library. As a data scientist, you should know how to create, index, add and delete Numpy arrays, As it is very helpful in data preparation and cleaning process.

Alternatively to

image = image[..., np.newaxis]

in @dbliss' answer, you can also use numpy.expand_dims like

image = np.expand_dims(image, <your desired dimension>)

For example (taken from the link above):

x = np.array([1, 2])

print(x.shape)  # prints (2,)

Then

y = np.expand_dims(x, axis=0)

yields

array([[1, 2]])

and

y.shape

gives

(1, 2)

Adding dimensions to numpy.arrays: newaxis v.s. reshape v.s. , This post demonstrates 3 ways to add new dimensions to numpy.arrays using numpy.newaxis, reshape, or expand_dim. It covers these cases� Create a NumPy ndarray Object. NumPy is used to work with arrays. The array object in NumPy is called ndarray. We can create a NumPy ndarray object by using the array() function.

You could just create an array of the correct size up-front and fill it:

frames = np.empty((480, 640, 3, 100))

for k in xrange(nframes):
    frames[:,:,:,k] = cv2.imread('frame_{}.jpg'.format(k))

if the frames were individual jpg file that were named in some particular way (in the example, frame_0.jpg, frame_1.jpg, etc).

Just a note, you might consider using a (nframes, 480,640,3) shaped array, instead.

https://docs.scipy.org/doc/numpy-1.17.0/reference/, Expand the shape of an array. Insert a new axis that will appear at the axis position in the expanded array shape. Note. Previous to NumPy 1.13.0, neither axis� Add array element. You can add a NumPy array element by using the append() method of the NumPy module. The syntax of append is as follows: numpy.append(array, value, axis) The values will be appended at the end of the array and a new ndarray will be returned with new and old values as shown above.

Pythonic

X = X[:, :, None]

which is equivalent to

X = X[:, :, numpy.newaxis] and X = numpy.expand_dims(X, axis=-1)

But as you are explicitly asking about stacking images, I would recommend going for stacking the list of images np.stack([X1, X2, X3]) that you may have collected in a loop.

If you do not like the order of the dimensions you can rearrange with np.transpose()

numpy.expand_dims — NumPy v1.13 Manual, It is a little brain-bending, because it operates via array slicing: >>> import numpy as np. >>> v = np.array([0, 3]) >>> v.shape (2,) >>> # Insert a new length 1� Given numpy array, the task is to add rows/columns basis on requirements to numpy array. Let’s see a few examples of this problem. Method #1: Using np.hstack() method

You can use np.concatenate() specifying which axis to append, using np.newaxis:

import numpy as np
movie = np.concatenate((img1[:,np.newaxis], img2[:,np.newaxis]), axis=3)

If you are reading from many files:

import glob
movie = np.concatenate([cv2.imread(p)[:,np.newaxis] for p in glob.glob('*.jpg')], axis=3)

Adding length 1 dimensions with newaxis — Functional MRI methods, Insert a new axis that will appear at the axis position in the expanded array shape . Syntax: numpy.expand_dims(a, axis) NumPy manipulation:� Iterating Array With Different Data Types. We can use op_dtypes argument and pass it the expected datatype to change the datatype of elements while iterating.. NumPy does not change the data type of the element in-place (where the element is in array) so it needs some other space to perform this action, that extra space is called buffer, and in order to enable it in nditer() we pass flags

NumPy Array manipulation: expand_dims() function, New shape will be will be (3, 1, 4). Pictorial Presentation: Python NumPy: Insert a new axis within a 2-D array. Sample Solution:- Python Code: Shape of numpy.ndarray: shape. The shape (= size of each dimension) of numpy.ndarray can be obtained as a tuple with attribute shape.. Even in the case of a one-dimensional array, it is a tuple with one element instead of an integer value.

NumPy: Insert a new axis within a 2-D array, Insert a new axis, corresponding to a given position in the array shape. Parameters: a : array_like. Input array. axis : int. Position� numpy.expand_dims¶ numpy.expand_dims (a, axis) [source] ¶ Expand the shape of an array. Insert a new axis that will appear at the axis position in the expanded array shape. Parameters a array_like. Input array. axis int or tuple of ints. Position in the expanded axes where the new axis (or axes) is placed.

numpy.expand_dims — NumPy v1.9 Manual, Learn how to deal with Numpy matrix dimensionality using np.reshape, It expands the shape of an array by inserting a new axis at the axis position in the expanded array shape create a column vector by adding second dimension. 1) To add a dimension to an array a of arbitrary dimensionality: b = numpy.reshape (a, list (numpy.shape (a)) + [1]) Explanation: You get the shape of a, turn it into a list, concatenate 1 to that list, and use that list as the new shape in a reshape operation.

Comments
  • Currently, numpy.newaxis is defined to be None (in file numeric.py), so equivalently you could use `image = image[..., None].
  • Don't use None. Use np.newaxis because explicit is better than implicit.
  • How can that be? None does not imply anything. It is explicit. It is None. Stated clearly.None is a thing in python. There is no doubt. None is the last detail, you cannot go deeper. On the other hand, numpy.newaxis implies None. It is, essentially, None. It is None. But is None implicitly. It is None though not directly expressed as None. Explicit stated clearly and in detail, leaving no room for confusion or doubt. Implicit suggested though not directly expressed. I must add, that, from an API perspective, it is safer to use numpy.newaxis.
  • Guess here, being explicit refers to the "coder intent" rather than to the syntactical/semantical clarity.
  • how to add values in the new dimention? if i do y[1,0] it gives index out of bounds error. y[0,1] is accessible
  • @weima: Not fully sure what you are after. What is your desired output?
  • I think this is the way to go. if you use the concatenation you will need to move the array in memory every time you add to it. for 100 frames that should not matter at all, but if you want to go to larger videos. BTW, I would have used the number of frames as the first dimension so have a (100,480,640,3) array that way you can access individual frames (what is usually want you will want to look at, right?) easier (F[1] instead of F[:,:,:,1]). Of course performance wise it should not matter at all.