使用Python中的PIL将像素更改为灰度

时间:2017-03-01 19:14:54

标签: python image pixel

我正在尝试将RGB图片转换为灰度图片。我不想使用image.convert('L')。这只是显示原始图像而不改变任何东西。我尝试在“红色,绿色,蓝色= 0,0,0”行中添加不同的数字,这确实会改变图像的颜色,但这不是我想要的。

    import PIL
    from PIL import Image

    def grayscale(picture):
        res=PIL.Image.new(picture.mode, picture.size)
        width, height = picture.size

        for i in range(0, width):
            for j in range(0, height):
                red, green, blue = 0,0,0
                pixel=picture.getpixel((i,j))

                red=red+pixel[0]
                green=green+pixel[1]
                blue=blue+pixel[2]
                avg=(pixel[0]+pixel[1]+pixel[2])/3
                res.putpixel((i,j),(red,green,blue))

        res.show()
    grayscale(Image.show('flower.jpg'))

2 个答案:

答案 0 :(得分:2)

import PIL
from PIL import Image

def grayscale(picture):
    res=PIL.Image.new(picture.mode, picture.size)
    width, height = picture.size

    for i in range(0, width):
        for j in range(0, height):
            pixel=picture.getpixel((i,j))
            avg=(pixel[0]+pixel[1]+pixel[2])/3
            res.putpixel((i,j),(avg,avg,avg))
    res.show()

image_fp = r'C:\Users\Public\Pictures\Sample Pictures\Tulips.jpg'
im = Image.open(image_fp)
grayscale(im)

答案 1 :(得分:1)

您所犯的错误是您没有使用灰度值更新像素值。通过平均R,G,B值来计算灰度。

您可以在灰度函数中替换它:

def grayscale(picture):
    res=PIL.Image.new(picture.mode, picture.size)
    width, height = picture.size
    for i in range(0, width):
            for j in range(0, height):
                pixel=picture.getpixel((i,j))
                red= pixel[0]
                green= pixel[1]
                blue= pixel[2]
                gray = (red + green + blue)/3
                res.putpixel((i,j),(gray,gray,gray))
    res.show()