Python Pillow - 使用NumPy进行机器学习



使用 NumPy 进行图像处理是图像处理任务中的一种常见做法。 NumPy 提供了一个强大的数组操作库,可以补充 Pillow 的图像处理功能。本教程演示如何将 Pillow 与 NumPy 结合使用以实现高效的图像处理。

安装

在继续之前,请确保已安装 NumPy。以管理员身份打开命令提示符并执行以下命令:

pip install numpy

注意 - 此命令仅在您已安装并更新 PIP 的情况下有效。

从 NumPy 数组创建图像

在将 NumPy 数组用作图像时,可以使用 Image.fromarray() 函数从导出数组接口的对象(通常使用缓冲区协议)创建图像内存。如果输入数组 (obj) 在内存中是连续的,Pillow 可以直接使用数组接口。如果数组不是连续的,Pillow 将使用 tobytes 方法,并且将使用 frombuffer() 创建图像。以下是 fromarray() 函数的语法:

PIL.Image.fromarray(obj, mode=None)

其中:

  • obj - 导出数组接口的对象。这通常是 NumPy 数组,但它可以是任何公开所需接口的对象。

  • mode (可选) - mode 参数指定生成的图像的颜色模式或像素格式。如果未提供,则从输入数组的类型推断模式。

需要注意的是,Pillow 模式(颜色模式)并不总是直接对应于 NumPy 数据类型 (dtypes)。Pillow 模式包括 1 位像素、8 位像素、32 位有符号整数像素和 32 位浮点像素的选项。模式要么显式指定,要么从输入数组的 dtype 推断。

示例

在此示例中,创建一个 NumPy 数组,然后使用 Image.fromarray() 从 NumPy 数组创建 Pillow Image。生成的图像是 Pillow Image 对象,可以进一步处理或保存。

from PIL import Image
import numpy as np

# Create a NumPy array
arr = np.zeros([150, 250, 3], dtype=np.uint8)
arr[:,:100] = [255, 128, 0]
arr[:,100:] = [0, 0, 255]

# Create a Pillow Image from the NumPy array
image = Image.fromarray(arr)

# Display the created image
image.show()

输出

created image

示例

这是另一个通过显式指定模式从 NumPy 数组创建 Pillow Image 的示例。

from PIL import Image
import numpy as np

# Create a NumPy array
arr = np.zeros([250, 350, 3], dtype=np.uint8)
arr[:100, :200] = 250

# Create a Pillow Image from the NumPy array by explicitly specifying the mode
image = Image.fromarray(arr, mode='RGB')

# Display the created image
image.show()

输出

created image black and white

示例

此示例通过显式指定 mode 等于“L”来从 numpy 二维数组创建灰度图像。

from PIL import Image
import numpy as np

# Create a NumPy array
arr = np.zeros([300, 700], dtype=np.uint8)
arr[100:200, 100:600] = 250

# Create a Pillow grayscale Image from the NumPy array 
# by explicitly specifying the mode
image = Image.fromarray(arr, mode='L')
print("Pixel values of image at (150, 150) of the grayscale image is:", image.getpixel((150, 150)))

# Display the created image
image.show()

输出

Pixel values of image at (150, 150) of the grayscale image is: 250
grayscale image

从 Pillow Image 创建 NumPy 数组

可以使用 numpy.asarray() 函数将 Pillow 图像转换为 NumPy 数组。但是,需要注意的是,将 Pillow 图像转换为数组时,只有像素值会被传输。这意味着某些图像模式(如 P 和 PA)在转换过程中会丢失其调色板信息。

示例

以下示例演示如何将 Pillow 图像转换为 NumPy 数组。

from PIL import Image
import numpy as np

# Open an image as a pillow image object
image = Image.open("Images/TP logo.jpg")

# Convert the Pillow image to a NumPy array
result = np.asarray(image)

# Display the type, shape and dtype of the NumPy array
print("Type:", type(result))
print("Shape:", result.shape)
print("Dtype:", result.dtype)

输出

Type: <class 'numpy.ndarray'>
Shape: (225, 225, 3)
Dtype: uint8
广告
© . All rights reserved.