views:

989

answers:

4

I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.

+4  A: 

You can use PyPNG. It's a pure Python (no dependencies) open source PNG encoder/decoder and it supports writing NumPy arrays as images.

dF
+1  A: 

If you have matplotlib, you can do:

import matplotlib.pyplot as plt
plt.imshow(matrix) #Needs to be in row,col order
plt.savefig(filename)
DopplerShift
A: 

matplotlib svn has a new function to save images as just an image -- no axes etc. it's a very simple function to backport too, if you don't want to install svn (copied straight from image.py in matplotlib svn, removed the docstring for brevity):

def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None):
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure

    fig = Figure(figsize=arr.shape[::-1], dpi=1, frameon=False)
    canvas = FigureCanvas(fig)
    fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin)
    fig.savefig(fname, dpi=1, format=format)
Autoplectic
A: 

If you have numpy, then you have scipy:

import scipy
scipy.misc.imsave('outfile.jpg', image_array)

I think this is a more natural solution since it is enclosed within numpy/scipy. At least, that's what I do.

Steve
imsave lives in .../scipy/misc/pilutil.py which uses PIL
Denis
Ah, I was not aware. Thank you for the reference.
Steve