Skip to main content
 首页 » 编程设计

python之如何在 numpy 数组中添加维度 (125, 125) 至 (125, 125, 1)

2025年05月04日20三少

我正在使用 OpenCV python 加载图像作为灰度图像,因为图像的形状是 (125, 125)。但是,我需要形状为 (125, 125, 1),其中 1 表示 channel 数(1 因为它是灰度)。

img = cv2.imread('/path/to/image.png', 0) 
print(img.shape) 
# prints (125, 125) 

现在,我需要将 img 的形状转换为 (125, 125, 1)

请您参考如下方法:

最简单的方法是使用 numpy indexing and np.newaxis :

img = np.ones((125, 125)) # img.shape: (125, 125) 
img_3d = img[..., np.newaxis] # img_3d.shape: (125, 125, 1) 

如果您只需要额外的维度来将数据传递给另一个函数,这将特别方便,因此您可以只传递花式索引数组。