python basic tutorial: Python convert an RGB image into a gray image example Pytho

Following small Python will bring an example of RGB image is converted to grayscale images Pytho for everyone. It has a good reference value. I hope to be helpful. Come and see, to follow the small series together
questions:

I am trying to use matplotlib read RGB image and convert it to grayscale.

In matlab, I use this:

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

In matplotlib tutorial they do not cover it. They just read in the image

import matplotlib.image as mpimg
img = mpimg.imread('image.png')

Then they sliced ​​arrays, but this is not from what I understand of the RGB conversion to grayscale.

lum_img = img[:,:,0]

edit:

I find it hard to believe numpy or matplotlib no built-in function to convert from rgb to gray. This is not the common image processing operations in it?

I wrote a very simple function, it can use the imported image imread within 5 minutes. It is very inefficient, but that is why I hope that the built-Major.

Sebastian improved my capabilities, but I still hope to find a built-in.

matlab's (NTSC / PAL) to achieve:

import numpy as np
  
def rgb2gray(rgb):
  
 r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
 gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
  
 return gray

Reply:

How to use PIL

from PIL import Image
img = Image.open('image.png').convert('LA')
img.save('greyscale.png')

Matplotlib and use the formula

Y' = 0.299 R + 0.587 G + 0.114 B

You can do this:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
  
def rgb2gray(rgb):
 return np.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()

Finally, we recommend a very wide python learning resource gathering, [click to enter] , here are my collection before learning experience, study notes, there is a chance of business experience, and calmed down to zero on the basis of information to project combat , we can at the bottom, leave a message, do not know to put forward, we will study together progress
over this Python RGB image is converted to grayscale image is an example Pytho small series to share the entire contents of all of the

Published 20 original articles · won praise 4 · views 20000 +

Guess you like

Origin blog.csdn.net/haoxun11/article/details/104931764