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

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


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 npfrom PIL import Image# gradient between 0 and 1 for 256*256array = np.linspace(0,1,256*256)# reshape to 2dmat = np.reshape(array,(256,256))# Creates PIL imageimg = Image.fromarray(np.uint8(mat * 255) , 'L')img.show()

Makes a clean gradient

vs

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

Has the same kind of artifacting.


If I understood you question, you want to get a grayscale image using PIL.

If this is the case, you do not need to multiply each pixels by 255.

The following worked for me

import numpy as npfrom PIL import Image# Creates a random image 100*100 pixelsmat = np.random.random((100,100))# Creates PIL imageimg = Image.fromarray(mat, 'L')img.show()


im = Image.fromarray(np.uint8(mat), 'L')

or

im = Image.fromarray(np.uint8(mat))

Apparently it accepts type np.uint8(insert array here), also may be able to remove 'L' for conciseness.