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'))
Hawk Student
  • 147
  • 3
  • 9
  • Taking mean of RGB is not a good method see [here](https://en.wikipedia.org/wiki/Grayscale) and [here](https://stackoverflow.com/q/12201577/2325279) – Petr Vepřek Jan 23 '21 at 11:47

2 Answers2

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)
plasmon360
  • 4,109
  • 1
  • 16
  • 19
1

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()
Avinash Hindupur
  • 421
  • 5
  • 15