我有一个Numpy数组类型的矩阵。我怎么把它作为映像写到磁盘上呢?任何格式都可以(png, jpeg, bmp…)一个重要的限制是PIL不存在。
当前回答
scipy。Misc给出关于imsave函数的弃用警告,并建议使用imageio代替。
import imageio
imageio.imwrite('image_name.png', img)
其他回答
matplotlib:
import matplotlib.image
matplotlib.image.imsave('name.png', array)
适用于matplotlib 1.3.1,我不知道低版本。从文档字符串:
Arguments:
*fname*:
A string containing a path to a filename, or a Python file-like object.
If *format* is *None* and *fname* is a string, the output
format is deduced from the extension of the filename.
*arr*:
An MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA) array.
您可以使用PyPNG。它是一个纯Python(无依赖)开源PNG编码器/解码器,它支持将NumPy数组写入图像。
为了将numpy数组保存为image,你有几个选择:
1)其他优点:OpenCV
进口cv2 cv2。Imwrite('扩展名为。jpg ', numpy_array)
2) Matplotlib
从matplotlib导入pyplot作为PLT plt。Imsave('扩展名为。jpg ', numpy_array)
3)药片
来自PIL import Image image = image .fromarray(numpy_array) 的形象。保存('扩展名为。jpg)')
4)...
你可以使用这段代码将你的Npy数据转换成图像:
from PIL import Image
import numpy as np
data = np.load('/kaggle/input/objects-dataset/nmbu.npy')
im = Image.fromarray(data, 'RGB')
im.save("your_file.jpeg")
python有opencv(文档在这里)。
import cv2
import numpy as np
img = ... # Your image as a numpy array
cv2.imwrite("filename.png", img)
如果需要进行除保存以外的更多处理,则非常有用。