简体   繁体   English

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

[英]Saving a Numpy array as an image (instructions)

I found my answer in a previous post: Saving a Numpy array as an image .我在上一篇文章中找到了答案: 将 Numpy 数组保存为图像 The only problem being, there isn't much instruction on using the PyPNG module.唯一的问题是,没有太多关于使用 PyPNG 模块的说明。

There are only a few examples online-- http://packages.python.org/pypng/ex.html#numpy http://nullege.com/codes/search/png.Writer.write目前只有几个例子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:但是根据这样的 .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

Here's where the error happens in my code, PCA_tool.py (The error comes after "folder.write(outfilename, PrincipalComponent"):这是我的代码 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)

I'm trying to save a 8400 element numpy.ndarray as an=80 column, m=105 row greyscale png image.我正在尝试将一个 8400 元素的 numpy.ndarray 保存为 an=80 列,m=105 行灰度 png 图像。

Thanks,谢谢,

You might be better off using PIL:使用 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')

An update to the answer is in order 答案的更新是有序的

rescaled = np.uint8(b)

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

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

It would be best to use scipy for it.最好使用 scipy。

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

Full documentation is here: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.misc.imsave.html完整文档在这里: https : //docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.misc.imsave.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM