迹忆客 专注技术分享

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

将 PIL 图像转换为 NumPy 数组

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

本教程将讨论在 Python 中将 PIL 图像转换为 3 维 NumPy 数组的方法。


在 Python 中使用 numpy.array() 函数将 PIL 图像转换为 NumPy 数组

PIL 用于在 Python 中对图像执行各种操作。枕头库未预先安装 Python 编程语言。因此,我们必须先安装它。下面给出了安装枕头库的命令。

pip install Pillow

如果要将 PIL 库读取的图像转换为 NumPy 数组,可以使用 numpy.array() 函数。numpy.array() 函数创建并初始化 numpy 数组。numpy.array() 函数会将 PIL 图像转换为 3 维数组。请参见以下代码示例。

import numpy as np
from PIL import Image

img = Image.open("NASA.jpg")
imgArray = np.array(img)
print(imgArray.shape)

输出:

(90, 240, 3)

在上面的代码中,我们使用 numpy.array() 函数将 PIL 图像 img 转换为三维 NumPy 数组 imgArray。我们使用 Python 中的 Image.open() 函数读取变量 img 中的图像。然后,我们在 Python 中使用 numpy.array() 函数将 img 转换为 NumPy 数组 imgArray。最后,我们使用 print() 函数打印了 imgArray 的形状。


在 Python 中使用 numpy.asarray() 函数将 PIL 图像转换为 NumPy 数组

我们还可以使用 numpy.asarray() 函数来实现与上一个示例相同的目标。numpy.asarray() 函数还创建并初始化一个 numpy 数组。通过将图像传递给 numpy.asarray() 函数,我们可以将 PIL 图像转换为 numPy 数组。请参见以下代码示例。

import numpy as np
from PIL import Image

img = Image.open("NASA.jpg")
imgArray = np.asarray(img)
print(imgArray.shape)

输出:

(90, 240, 3)

在上面的代码中,我们使用 python 中的 numpy.array() 函数将 PIL 图像 img 转换为三维 NumPy 数组 imgArray。我们在 Python 中使用 Image.open() 函数将 img 变量加载到了 img 变量中。然后,我们在 Python 中使用 numpy.asarray() 函数将 img 图像转换为 NumPy 数组 imgArray。最后,我们使用 print() 函数打印了 imgArray 的形状。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便