gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:24 24 4
gpt4 key购买 nike

我正在使用 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)

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

关于python - 如何在 numpy 数组中添加维度? (125, 125) 至 (125, 125, 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54176492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com