在Python中将numpy.ndarray保存为图像

8
b=ndimage.gaussian_filter(imagefile,5)   

作为一个刚接触Python的人,我无法理解这个问题。
如何将类型为“numpy.ndarray”的b保存为图像?

我尝试了以下方法:
1.

im = Image.fromarray(b)   
im.save("newfile.jpeg")   
错误: TypeError("无法处理此数据类型") 2.
imsave('newfile.jpg', b)

错误: ValueError: 'arr' 没有适合任何一种模式的数组形状。

ndarray 保存为图像的正确方法是什么?

编辑:

已解决:

im = Image.fromarray(b)    

im.save('newfile.jpeg') 工作了,我加载图片的方法是错误的。

技术相关内容请留给我翻译吧!
file = Image.open("abc.jpg")      
imagefile = file.load()     

// 我在加载图像文件后使用了imagefile,但这并不能使重构的图像形状正确。

// 相反,如果我直接使用文件(即在打开后),我可以通过上述方法保存。

1个回答

6
我认为最好的方法是使用matplotlibimshow函数。
使用image库:
import Image
import numpy as np

x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)

im = Image.fromarray(x)
im.save('test.png')

Matplotlib版本:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
plt.imshow(x) 
plt.savefig("array")

ndarray的输出结果 希望这有所帮助!


让我试试,我想避免导入更多的库来保存一个数组为图像。 - sat
你可以添加之前保存图像的答案,我可以按照那种方式保存它,只要我正确读取了图像,我已经编辑了问题。 - sat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接