Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+5 votes
in Python by (320 points)
recategorized by

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. 

4 Answers

+5 votes
by (10.9k points)
edited by

If you want to save a Numpy array as an 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 - For reading

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


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.


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,


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:


                    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
by (580 points)

You can try this code with matplotlib:

import matplotlib 



+1 vote
by (200 points)

given a numpy array "A":

from PIL import Image
im = Image.fromarray(A)"your_file.jpeg")

you can replace "jpeg" with almost any format you want.

0 votes
by (106k points)

You can use OpenCV:-

import cv2

import numpy as np

cv2.imwrite("filename.png", np.zeros((10,10)))

You can use the following video tutorials to clear all your doubts:-

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

Related questions

0 votes
1 answer
asked Sep 27, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
4 answers

Browse Categories