Hawk Student
Hawk Student

Reputation: 147

Changing pixels to grayscale using PIL in Python

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

Upvotes: 0

Views: 5544

Answers (2)

Avinash Hindupur
Avinash Hindupur

Reputation: 451

The mistake you are doing is you are not updating the pixel values with grayscale values. Gray is calculated by averaging R, G, B values.

You can replace with this in grayscale function:

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

Upvotes: 1

plasmon360
plasmon360

Reputation: 4199

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)

Upvotes: 2

Related Questions