gpt4 book ai didi

python - 如何在 python 中将黑白图像转换为 3 维数组?

转载 作者:太空狗 更新时间:2023-10-30 02:08:20 25 4
gpt4 key购买 nike

我有 RGB 格式或灰度格式的图像(我通过 Gimp 转换它,比方说),现在每次我以灰度加载图像,或者只是将其转换为灰度格式时,形状总是显示 [height, width]没有三维(颜色 channel 数)。

我知道通常黑白图像以这种格式存储,但我特别需要 [height, width, 1] 图像形状,你会得到的那个,比方说:

numpy.zeros(shape=[400, 400, 1])

最佳答案

您始终可以使用 np.expand_dims 添加“空”维度:

>>> a2d = np.ones((100, 200))
>>> a3d = np.expand_dims(a2d, axis=2)
>>> a3d.shape
(100, 200, 1)

或者使用 Nonenp.newaxis 进行切片:

>>> a2d[..., None].shape  # instead of "..." (Ellipsis) you could also use `[:, :, None]`
(100, 200, 1)

我更喜欢 np.expand_dims,因为它比切片更明确一点。


如果你有条件地需要它,首先检查arr.ndim:

if arr.ndim == 2:
arr = np.expand_dims(arr, axis=2)

关于python - 如何在 python 中将黑白图像转换为 3 维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43853524/

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