python - 从 PIL 图像转换后,Numpy 数组不显示灰度图像的颜色尺寸

标签 python numpy python-imaging-library

我正在尝试使用以下代码片段将 RGB 图像转换为灰度图像,然后转换为 numpy 数组:

img = Image.open("image1.png")
img = img.convert('L')
img = np.array(img, dtype='f')
print(img.shape)

结果是形状为 (128, 128) 的 numpy 数组。无论如何,我是否可以将灰度图像转换为 numpy 数组,以便它也具有颜色 channel ,即形状为 (128, 128, 1)?

最佳答案

就像@Mark在评论中提到的那样,如果您的数组使用newaxis,则在末尾添加一个维度:

img=img[...,None]

None 的作用与 np.newaxis 类似。它不会创建颜色,而是添加类似于单 channel 图像的尺寸。

关于python - 从 PIL 图像转换后,Numpy 数组不显示灰度图像的颜色尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64568012/

相关文章:

python - 使用OIL自动旋转手机和加速度计拍摄的照片

python - pymssql 抛出 ImportError : No module named _mssql when build app with py2exe

Python 3.7 阻碍其他 Python 版本在虚拟环境中的使用

python - 如何将 Numpy 数组切片到边界?

python - 在 python 中导入我的 cythonized 包

python - 在Python中为图像添加灯光效果

python - 代码未读取文件,错误对象 Len() MASTERLIST

python - Panda的左合并: resulting table has more rows,防止重复

python - Numpy/Python 一次过滤多列

python - 在 pyglet 或 PIL/python 中从远程服务器加载图像