首页 > 解决方案 > 如何在numpy数组中添加维度?(125, 125) 到 (125, 125, 1)

问题描述

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

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

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

标签: pythonnumpy

解决方案


尝试np.expand_dims

In [1]: import numpy as np

In [2]: img = np.ones((125, 125))

In [3]: img.shape
Out[3]: (125, 125)

In [4]: img = np.expand_dims(img, axis=-1)

In [5]: img.shape
Out[5]: (125, 125, 1)

推荐阅读