迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中将 NumPy 数组转换为 PIL 图像

作者:迹忆客 最近更新:2023/03/17 浏览次数:

本篇文章解释了我们如何使用 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()

输出:

将 NumPy 数组转换为 PIL 图像 Python

它将使用 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() 

输出:

将自创的 NumPy 数组转换为 PIL 图像 Python

在这里,我们创建一个大小为 400x400 的 NumPy 数组,其随机数范围为 0255,然后使用 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()

输出:

将 NumPy 数组转换为 PIL 图像 Python 应用 Matplotlib Colormap

它应用了 Matplotlib 包中的 plasma colormap。要将一个 colormap 应用到一个图像上,我们首先要将 array 归一化,最大值为 1。在上面的例子中,image_array 中元素的最大值是 255。因此,我们将 image_array 除以 255 进行归一化。

然后,我们将 colormap 应用到 image_array 中,并再次乘以 255。然后,我们使用 np.uint8() 方法将元素转换为 int 格式。最后,我们使用 Image.fromarray() 函数将数组转换为图像。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便