Search code examples
pythonimagegrayscale

Image Processing: Converting Image to Grayscale


I am new to Python and am having trouble converting this image to grayscale after googling the formula. Did I apply it wrongly? My image is tinted green no matter what I try.

0.2989 * R + 0.5870 * G + 0.1140 * B

    import image

img= image.Image("luther.jpg")
win= image.ImageWin(img.getWidth(), img.getHeight())
img.draw(win)
img.setDelay(1,100)

for row in range(img.getHeight()):
    for col in range(img.getWidth()):
        p=img.getPixel(col, row)
        newRed= 0.2989*p.getRed()
        newGreen= 0.5870*p.getGreen()
        newBlue= 0.1140*p.getBlue()
        newpixel= image.Pixel(newRed, newGreen, newBlue)
        img.setPixel(col, row, newpixel)
        
img.draw(win)
win.exitonclick()enter code here

Image


Solution

  • Okay, I have figured it out. I tried to solve this problem without any libraries and here is my simple solution:

    import image
    
    img= image.Image("luther.jpg")
    win= image.ImageWin(img.getWidth(), img.getHeight())
    img.draw(win)
    img.setDelay(1,100)
    
    for row in range(img.getHeight()):
        for col in range(img.getWidth()):
            p=img.getPixel(col, row)
            grayscale= (p.getRed()+ p.getGreen()+ p.getBlue())/3
            newRed= grayscale
            newGreen= grayscale
            newBlue= grayscale
            newpixel= image.Pixel(newRed, newGreen, newBlue)
            img.setPixel(col, row, newpixel)
            
    img.draw(win)
    win.exitonclick()