2 views
in Python

In matplotlib,I was trying to read an RGB image and trying to convert it to grayscale

let the image file name be "image.png"

Even in the Matplotib tutorial they didn't cover it.

import matplotlib.image as mpimg

then it will slice the array. but the thing is, its not the same thing as converting the RGB to grayscale from what I understand

lum_img=img[:,:,0]

I couldn't believe that matplotlib or numpy doesn't have inbuilt function for converting rgb to gray.So can anyone just tell me, how to convert an RGB image into grayscale in python ?

by (26.4k points)
edited by

You can approach it with Pillow:

from PIL import Image

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

img.save('greyscale.png')

With the help of 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 np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])

gray = rgb2gray(img)

plt.imshow(gray, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)

plt.show()

You can also become a python expert. By joining this python certification course

To know more topics related to python, you can just look at the following video tutorial: