Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (280 points)

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"

img = rgb2gray(imread('image.png'));

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

import matplotlib.image as mpimg

img = mpimg.imread('image.png')

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


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 ?

1 Answer

0 votes
by (26.4k points)
edited by

You can approach it with Pillow:

from PIL import Image

img ='image.png').convert('LA')'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[...,: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)

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:

Browse Categories