How does python convert an RGB image to a pytho grayscale image?

Source: Internet
Author: User
Tags matplotlib tutorial

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.

1 lum_img =img[:,:,0]

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.