How can I convert an RGB image into grayscale in Python?

前端 未结 12 1325
Happy的楠姐
Happy的楠姐 2020-11-22 04:43

I\'m trying to use matplotlib to read in an RGB image and convert it to grayscale.

In matlab I use this:

img = rgb2gray(imread(\'image.p         


        
12条回答
  •  猫巷女王i
    2020-11-22 05:12

    How about doing it with Pillow:

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

    Using 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])
    
    img = mpimg.imread('image.png')     
    gray = rgb2gray(img)    
    plt.imshow(gray, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
    plt.show()
    

提交回复
热议问题