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()
函数将数组转换为图像。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串