How can I add new dimensions to a Numpy array?

Chris picture Chris · Jun 30, 2013 · Viewed 162.2k times · Source

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?

Answer

dbliss picture dbliss · Sep 10, 2014

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]