gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:16:14 26 4
gpt4 key购买 nike

我在之前的帖子中找到了答案: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 图像。

谢谢,

最佳答案

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

关于python - 将 Numpy 数组保存为图像(说明),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6915106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com