# Saving a Numpy array as an image

313    Asked by BenPHILLIPS in QA Testing , Asked on Jun 9, 2021

Please suggest currently I have a matrix in the type of a Numpy array, so how would I write it to disk as an image, it can be of any format png, jpeg, bmp..., just remember one important constraint that here PIL is not present.

How to save numpy array as image?

If you want to save Numpy array as image you can use PyPNG .It's a pure python open-source encoder/decoder with no dependencies when PIL is not present.

For better understanding here I am explaining you everything in details :

PNG to NumPy array

Convert each PyPNG row to a 1-D numpy array then stack those arrays together to create a 2-D array.

Ex-

Let pngdata be a row iterator returned from png.Reader.asDirect() and then try the following code which will generate a 2-D array:

image_2d = numpy.vstack(itertools.imap(numpy.uint16, pngdata))

Here, the use of numpy.unit16 creates an array with data type numpy.unit16 which is mainly suitable for bit depth 16 images. You can replace it with numpy.uint8 that will be suitable for bit depth 8 images.

Reshaping:

There are some operation which requires image data in 3-D array. Try the following to code to generate a 3-D array:

image_3d = numpy.reshape(image_2d,

(row_count,column_count,plane_count))

To convert NumPy array to PNG -

You should first reshape the NumPy array data into a 2-D array. Since we know NumPy array acts as an iterator over its rows:

pngWriter.write(pngfile,

numpy.reshape(image_3d, (-1, column_count*plane_count)))

The above code may generate a warning but it is harmless, its just a bug.