Python 中将 NumPy 数组转换为 PIL 图像
本教程解释了我们如何使用 PIL 包中的 Image.fromarray() 将 NumPy 数组转换为 PIL 图像。Python Imaging Library (PIL)是 Python 中一个具有各种图像处理功能的库。
Image.fromarray() 函数将数组对象作为输入,并返回由数组对象制作的图像对象。
在 Python 中把一个 NumPy 数组转换为 PIL 图像
import numpy as np
from PIL import Image
image = Image.open("lena.png")
np_array = np.array(image)
pil_image = Image.fromarray(np_array)
pil_image.show()
输出:

它将使用 open() 方法从 Image 中读取当前工作目录下的图像 lena.png,并返回一个图像对象。
然后我们使用 numpy.array() 方法将这个图像对象转换为一个 NumPy 数组。
我们使用 Image.fromarray() 函数将该数组转换回 PIL 图像对象,最后使用 show() 方法显示该图像对象。
import numpy as np
from PIL import Image
array = np.random.randint(255, size=(400, 400), dtype=np.uint8)
image = Image.fromarray(array)
image.show()
输出:

在这里,我们创建一个大小为 400x400 的 NumPy 数组,其随机数范围为 0 到 255,然后使用 Image.fromarray() 函数将数组转换为 Image 对象,并使用 show() 方法显示 image。
用 Matplotlib Colormap 将 NumPy 数组转换为 PIL 图像 Python
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from matplotlib import cm
image_array = plt.imread("lena.jpg")
image_array = image_array / 255
image = Image.fromarray(np.uint8(cm.plasma(image_array) * 255))
image.show()
输出:

它应用了 Matplotlib 包中的 plasma colormap。要将一个 colormap 应用到一个图像上,我们首先要将 array 归一化,最大值为 1。在上面的例子中,image_array 中元素的最大值是 255。因此,我们将 image_array 除以 255 进行归一化。
然后,我们将 colormap 应用到 image_array 中,并再次乘以 255。然后,我们使用 np.uint8() 方法将元素转换为 int 格式。最后,我们使用 Image.fromarray() 函数将数组转换为图像。
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn