【问题标题】:Changing pixels to grayscale using PIL in Python在 Python 中使用 PIL 将像素更改为灰度
【发布时间】:2017-07-21 06:36:34
【问题描述】:

我正在尝试将 RGB 图片转换为灰度。我不想使用 image.convert('L')。这只是显示原始图像而不更改任何内容。我尝试在“red,green,blue=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'))

【问题讨论】:

  • 对 RGB 取平均值不是一个好方法,请参阅 here 和 here

标签: python image pixel


【解决方案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()

【讨论】:

    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-11
      • 2020-09-02
      • 2018-08-15
      • 1970-01-01
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      相关资源
      最近更新 更多