读取图片为灰度numpy数组,存回去

Read the picture as a grayscale numpy array, and save it back

我尝试了以下方法,希望看到源图像的灰度版本:

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.请注意,我在开头的代码中又添加了两行,以导入此代码正常工作所需的包(尽管图像处于离线状态)。