Converting an image to grayscale using numpy

后端 未结 3 1850
鱼传尺愫
鱼传尺愫 2021-01-13 15:11

I have an image represented by a numpy.array matrix nxm of triples (r,g,b) and I want to convert it into grayscale, , using my own function.

My

3条回答
  •  清酒与你
    2021-01-13 15:46

    Solution using apply_along_axis

    A solution can be achieved by using apply_along_axis:

    import numpy as np
    def grayscale(colors):
        """Return grayscale of given color."""
        r, g, b = colors
        return 0.07 * r + 0.72 * g + 0.21 * b
    
    image = np.random.uniform(255, size=(10,10,3))
    result = np.apply_along_axis(grayscale, 2, image)
    

    Examples

    10x10 image

    We can now proceed to visualise the results:

    from matplotlib import pyplot as plt
    plt.subplot(1,2,1)
    plt.imshow(image)
    plt.subplot(1,2,2)
    plt.imshow(result, cmap='gray')
    

    Textual example (2x2 image)

    To visualise the actual results in text I will use a smaller array, just a 2x2 image:

    image = np.random.uniform(250, size=(2,2,3))
    

    The content is:

    array([[[205.02229826, 109.56089703, 163.74868594],
        [ 11.13557763, 160.98463727, 195.0294515 ]],
    
       [[218.15273335,  84.94373737, 197.70228018],
        [ 75.8992683 , 224.49258788, 146.74468294]]])
    

    Let's convert it to grayscale, using our custom function:

    result = np.apply_along_axis(grayscale, 2, image)
    

    And the output of the conversion is:

    array([[127.62263079, 157.64461409],
       [117.94766108, 197.76399547]])
    

    We can visualise this simple example too, using the same code as above:

    Further suggestions

    If you want to apply your own custom function, then apply_along_axis is the way to go, but you should consider using purer numpy approaches such as the one suggested by Eric or, if possible, just load the black and white image using cv2 option:

    cv2.imread('smalltext.jpg',0)
    

提交回复
热议问题