I'm trying to use the matplotlib read RGB image and convert it to grayscale.
In MATLAB, I use this:
| 1 |
img =rgb2gray(imread(‘image.png‘)); |
In the Matplotlib tutorial they did not cover it. They just read in the image
| 12 |
importmatplotlib.image as mpimgimg =mpimg.imread(‘image.png‘) |
Then they slice the array, but this is not from what I know to convert RGB to grayscale.
Edit:
I find it hard to believe that numpy or matplotlib does not have built-in functions to convert from RGB to gray. Is this not a common operation in image processing?
I have written a very simple function that can use imported images within 5 minutes imread . This is very inefficient, but that's why I want a built-in professional implementation.
Sebastian has improved my functionality, but I still want to find a built-in one.
MATLAB (Ntsc/pal) Implementation:
| 12345678 |
importnumpy as npdefrgb2gray(rgb): r, g, b =rgb[:,:,0], rgb[:,:,1], rgb[:,:,2] gray =0.2989*r +0.5870*g +0.1140* b returngray |
Reply:
How to use PiL
| 123 |
fromPIL import Imageimg =Image.open(‘image.png‘).convert(‘LA‘)img.save(‘greyscale.png‘) |
Using Matplotlib and the formula
| 1 |
Y‘ =0.299 R + 0.587 G + 0.114B |
You can do this:
| 1234567891011 |
importnumpy as npimportmatplotlib.pyplot as pltimport matplotlib.image as mpimgdefrgb2gray(rgb): returnnp.dot(rgb[...,:3], [0.299, 0.587, 0.114])img = mpimg.imread(‘image.png‘) gray =rgb2gray(img) plt.imshow(gray, cmap =plt.get_cmap(‘gray‘))plt.show() |
How does python convert an RGB image to a pytho grayscale image?