在 Python 中将 NumPy 数组保存为图像

在 Python 中,numpy 模块用于处理数组。Python 中有许多可用的模块,这些模块使我们可以读取和存储图像。

可以将图像视为存储在具有相应颜色代码的特定位置的不同像素的数组。因此,我们可能会遇到需要将数组转换并保存为图像的情况。

在本教程中,我们将讨论如何将 numpy 数组另存为图像。

使用 Image.fromarray() 函数将一个 numpy 数组另存为图像

fromarray() 函数用于从导出数组的对象创建图像内存。然后,我们可以通过提供所需的路径和文件名将图像内存保存到我们所需的位置。

例如,

import numpy as np
from PIL import Image
array = np.arange(0, 737280, 1, np.uint8)
array = np.reshape(array, (1024, 720))
im = Image.fromarray(array)
im.save("filename.jpeg")

我们首先创建一个存储 RGB 颜色代码的数组,然后将其导出。我们可以在文件名中指定图像的所需格式。可以是 jpegpng 或任何其他常用的图​​像格式。这对于下面讨论的所有方法都是很常见的。

使用 imageio.imwrite() 函数将一个 numpy 数组另存为图像

较早之前,scipy 模块具有 imsave() 函数,可将 numpy 数组另存为图像。但是,在最近的版本中,它已被弃用,并且开始推荐使用 image.io() 中的 imwrite() 函数来执行此任务,并因其简单性而广受欢迎。

以下代码显示了如何使用此函数。

import imageio
import numpy as np
array = np.arange(0, 737280, 1, np.uint8)
array = np.reshape(array, (1024, 720))
imageio.imwrite('filename.jpeg', array)

使用 matplotlib.pyplot.imsave() 函数将一个 NumPy 数组另存为图像

matplotlib 模块有多种函数可用于处理图像。

imsave() 函数可以将数组另存为图像文件。

例如,

import matplotlib.pyplot as plt
import numpy as np
array = np.arange(0, 737280, 1, np.uint8)
array = np.reshape(array, (1024, 720))
plt.imsave('filename.jpeg', array)

使用 cv2.imwrite() 函数将一个 numpy 数组另存为图像

OpenCV 模块通常用于 Python 中的图像处理。该模块中的 imwrite() 函数可以将一个 numpy 数组导出为图像文件。

例如,

import cv2
import numpy as np
array = np.arange(0, 737280, 1, np.uint8)
array = np.reshape(array, (1024, 720))
cv2.imwrite('filename.jpeg', array)