将Numpy数组保存为图像(说明)

时间:2011-08-02 16:10:59

标签: python image numpy

我在上一篇文章中找到了答案:Saving a Numpy array as an image。唯一的问题是,没有太多关于使用PyPNG模块的指令。

网上只有几个例子 - http://packages.python.org/pypng/ex.html#numpy http://nullege.com/codes/search/png.Writer.write

但是我应该根据这样的.write错误做什么:

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

这是我的代码中发生错误的地方,PCA_tool.py(错误发生在“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)

我正在尝试将一个8400元素numpy.ndarray保存为n = 80列,m = 105行灰度png图像。

谢谢,

4 个答案:

答案 0 :(得分:22)

使用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')

答案 1 :(得分:1)

答案的更新是按顺序

rescaled = np.uint8(b)

通过https://stackoverflow.com/a/7700789/184085

答案 2 :(得分:1)

import matplotlib.pyplot as plt
import numpy as np
plt.imshow(np.random.random(100, 100))
plt.savefig('')

答案 3 :(得分:0)

最好使用scipy。

from scipy.misc import imsave
# x is the array you want to save 
imsave("image.png", x)

完整文档在此处:https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.misc.imsave.html