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

前端 未结 12 1117
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条回答
  • 2020-11-22 04:48

    The fastest and current way is to use Pillow, installed via pip install Pillow.

    The code is then:

    from PIL import Image
    img = Image.open('input_file.jpg').convert('L')
    img.save('output_file.jpg')
    
    0 讨论(0)
  • 2020-11-22 04:50
    image=myCamera.getImage().crop(xx,xx,xx,xx).scale(xx,xx).greyscale()
    

    You can use greyscale() directly for the transformation.

    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2020-11-22 04:59

    I came to this question via Google, searching for a way to convert an already loaded image to grayscale.

    Here is a way to do it with SciPy:

    import scipy.misc
    import scipy.ndimage
    
    # Load an example image
    # Use scipy.ndimage.imread(file_name, mode='L') if you have your own
    img = scipy.misc.face()
    
    # Convert the image
    R = img[:, :, 0]
    G = img[:, :, 1]
    B = img[:, :, 2]
    img_gray = R * 299. / 1000 + G * 587. / 1000 + B * 114. / 1000
    
    # Show the image
    scipy.misc.imshow(img_gray)
    
    0 讨论(0)
  • 2020-11-22 05:00

    Use img.Convert(), supports “L”, “RGB” and “CMYK.” mode

    import numpy as np
    from PIL import Image
    
    img = Image.open("IMG/center_2018_02_03_00_34_32_784.jpg")
    img.convert('L')
    
    print np.array(img)
    

    Output:

    [[135 123 134 ...,  30   3  14]
     [137 130 137 ...,   9  20  13]
     [170 177 183 ...,  14  10 250]
     ..., 
     [112  99  91 ...,  90  88  80]
     [ 95 103 111 ..., 102  85 103]
     [112  96  86 ..., 182 148 114]]
    
    0 讨论(0)
  • 2020-11-22 05:01

    You can always read the image file as grayscale right from the beginning using imread from OpenCV:

    img = cv2.imread('messi5.jpg', 0)
    

    Furthermore, in case you want to read the image as RGB, do some processing and then convert to Gray Scale you could use cvtcolor from OpenCV:

    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    0 讨论(0)
提交回复
热议问题