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

前端 未结 12 1122
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 04:56

    you could do:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    
    def rgb_to_gray(img):
            grayImage = np.zeros(img.shape)
            R = np.array(img[:, :, 0])
            G = np.array(img[:, :, 1])
            B = np.array(img[:, :, 2])
    
            R = (R *.299)
            G = (G *.587)
            B = (B *.114)
    
            Avg = (R+G+B)
            grayImage = img
    
            for i in range(3):
               grayImage[:,:,i] = Avg
    
            return grayImage       
    
    image = mpimg.imread("your_image.png")   
    grayImage = rgb_to_gray(image)  
    plt.imshow(grayImage)
    plt.show()
    

提交回复
热议问题