Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a Numpy array as an image (instructions)

I found my answer in a previous post: Saving a Numpy array as an image. The only problem being, there isn't much instruction on using the PyPNG module.

There are only a few examples online-- http://packages.python.org/pypng/ex.html#numpy http://nullege.com/codes/search/png.Writer.write

But what do I do in light of .write errors like this:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/png.py", line 638, in write
    nrows = self.write_passes(outfile, rows)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/png.py", line 783, in write_passes
    extend(row)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/png.py", line 780, in <lambda>
    return lambda sl: f(map(int, sl))
TypeError: argument 2 to map() must support iteration

Here's where the error happens in my code, PCA_tool.py (The error comes after "folder.write(outfilename, PrincipalComponent"):

#PrincipalComponent.save(path+'transform_'+str(each)+'.png', format='PNG')
outfilename = open(str(path)+'transformed/transform_'+str(each)+'.png', 'wb')
folder = png.Writer(m,n,greyscale=True)
folder.write(outfilename, PrincipalComponent)
outfilename.close()

sys.exit(0)

I'm trying to save a 8400 element numpy.ndarray as a n=80 column, m=105 row greyscale png image.

Thanks,

like image 220
Alvin Avatar asked Aug 02 '11 16:08

Alvin


1 Answers

You might be better off using PIL:

from PIL import Image
import numpy as np

data = np.random.random((100,100))

#Rescale to 0-255 and convert to uint8
rescaled = (255.0 / data.max() * (data - data.min())).astype(np.uint8)

im = Image.fromarray(rescaled)
im.save('test.png')
like image 63
Joe Kington Avatar answered Sep 20 '22 11:09

Joe Kington