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.

+5 votes

If you want to save a Numpy array as an image you can use PyPNG - https://github.com/drj11/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** - For reading

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))

**NumPy array to PNG **- For writing that you asked in that question above

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.

if you wish to know what is python visit this python tutorial and python interview questions.

+2 votes