# Saving a Numpy array as an image

4 views
in Python
recategorized

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.

by (10.9k points)
edited

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.

by (580 points)

You can try this code with matplotlib:

import matplotlib

matpotlib.image.imsave('name.png',

array)

+1 vote
by (200 points)

given a numpy array "A":

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

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

by (107k 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.