将图像转换为灰度输出错误的结果

时间:2018-06-18 02:39:53

标签: python arrays image-processing pillow grayscale

 def desaturate_image(self, image):
    desatimage = Image.new(image.mode, image.size)
    pixellist = []
    print(len(pixellist))
    for x in range(image.size[0]):
        for y in range(image.size[1]):
            r, g, b = image.getpixel((x, y))
            greyvalue = (r+g+b)/3
            greypixel = (int(round(greyvalue)), int(round(greyvalue)), int(round(greyvalue)))
            pixellist.append(greypixel)
    print(pixellist)
    desatimage.putdata(pixellist)
    return desatimage

我正在编写一个python方法,将作为参数传递的图像转换为灰度。我得到的结果虽然不对。这是输入和输出。哪里错了?

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

您首先使用错误的尺寸迭代像素 - 枕头图像是列主要顺序。所以你想要

...
for y in range(image.size[1]):
    for x in range(image.size[0]):
...

使您的像素列表按列存储像素。

这会给你

enter image description here

当然,您可以使用.convert方法更轻松地获取a greyscale representation,这会使用文档中提到的转换。

image.convert('L')

正如下面提到的那样,这为您提供了一个实际上处于灰度模式('L')的图像,而不是当前的答案,它使图像保持RGB模式('RGB')具有三重复数据。

相关问题