且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何向 Numpy 数组添加新维度?

更新时间:2023-11-30 12:20:22

您问的是如何向 NumPy 数组添加维度,以便随后可以增加该维度以容纳新数据.可以按如下方式添加维度:

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

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]