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

2024-04-24 08:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

 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


Tags: inimageselfforsizedefrangeint
1条回答
网友
1楼 · 发布于 2024-04-24 08:28:12

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

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

这样,像素列表按列存储像素。你知道吗

这给你

enter image description here


当然,您可以使用^{}方法更容易地获得a greyscale representation,它使用文档中提到的转换。你知道吗

image.convert('L')

正如下面提到的abarnert,这将为您提供一个实际处于灰度模式('L')的图像,而不是您当前的答案,该答案将图像保持在RGB模式('RGB'),并且具有三重重复数据。你知道吗

相关问题 更多 >