How can I convert an RGB image into grayscale in Python?

How about doing it with Pillow:

from PIL import Image
img ='image.png').convert('L')'greyscale.png')

If an alpha (transparency) channel is present in the input image and should be preserved, use mode LA:

img ='image.png').convert('LA')

Using matplotlib and the formula

Y' = 0.2989 R + 0.5870 G + 0.1140 B 

you could do:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def rgb2gray(rgb):
    return[...,:3], [0.2989, 0.5870, 0.1140])

img = mpimg.imread('image.png')     
gray = rgb2gray(img)    
plt.imshow(gray, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)

Leave a Comment