在Python中使用PIL将像素更改为灰度 [英] Changing pixels to grayscale using PIL in Python

查看:544
本文介绍了在Python中使用PIL将像素更改为灰度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将RGB图片转换为灰度图像.我不想使用image.convert('L').这只是显示原始图像,而没有进行任何更改.我尝试将不同的数字放在'red,green,blue = 0,0,0'行中,这确实会更改图像的颜色,但这不是我想要的.

I am trying to convert a RGB picture to grayscale. I do not want to use image.convert('L'). This just shows the original image without changing anything. I have tried putting different numbers in the 'red,green,blue=0,0,0' line which does change the color of the image but it is not what I want.

    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'))

推荐答案

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)

这篇关于在Python中使用PIL将像素更改为灰度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆