我尝试了以下操作,希望看到源图像的灰度版本:
from PIL import Image
import numpy as np
img = Image.open("img.png").convert('L')
arr = np.array(img.getdata())
field = np.resize(arr, (img.size[1], img.size[0]))
out = field
img = Image.fromarray(out, mode='L')
img.show()
但由于某种原因,整个图像几乎是由很多点组成,中间有黑色。为什么会发生这种情况?
最佳答案
当您使用 Pillow 对象中的图像数据创建 numpy
数组时,请注意该数组的默认精度为 int32
。我假设您的数据实际上是 uint8
因为实践中看到的大多数图像都是这种方式。因此,您必须明确确保该数组与图像中看到的类型相同。简而言之,在获取图像数据后确保数组为 uint8
,因此这将是代码中的第四行1。
arr = np.array(img.getdata(), dtype=np.uint8) # Note the dtype input
1。请注意,我在开始时在您的代码中添加了两行,以导入此代码运行所需的包(尽管图像处于离线状态)。
关于image - 将图片读取为灰度numpy数组,并保存回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39102051/