Converting 2D Numpy array of grayscale values to a PIL image

前端 未结 2 1583
Happy的楠姐
Happy的楠姐 2020-12-05 07:53

Say I have a 2D Numpy array of values on the range 0 to 1, which represents a grayscale image. How do I then convert this into a PIL Image object? All attempts so far have

2条回答
  •  臣服心动
    2020-12-05 08:02

    I think the answer is wrong. The Image.fromarray( ____ , 'L') function seems to only work properly with an array of integers between 0 and 255. I use the np.uint8 function for this.

    You can see this demonstrated if you try to make a gradient.

    import numpy as np
    from PIL import Image
    
    # gradient between 0 and 1 for 256*256
    array = np.linspace(0,1,256*256)
    
    # reshape to 2d
    mat = np.reshape(array,(256,256))
    
    # Creates PIL image
    img = Image.fromarray(np.uint8(mat * 255) , 'L')
    img.show()
    

    Makes a clean gradient

    vs

    import numpy as np
    from PIL import Image
    
    # gradient between 0 and 1 for 256*256
    array = np.linspace(0,1,256*256)
    
    # reshape to 2d
    mat = np.reshape(array,(256,256))
    
    # Creates PIL image
    img = Image.fromarray( mat , 'L')
    img.show()
    

    Has the same kind of artifacting.

提交回复
热议问题