Python Pillow 简明教程

Python Pillow - ML with Numpy

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

Installation

在继续之前,确保我们已安装 NumPy。以管理员模式打开命令提示符并执行以下命令 −

pip install numpy

Note − 仅当您已安装并更新 PIP 时,此命令才有效。

Creating image from Numpy Array

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

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

其中,

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

  2. mode (optional) − mode 参数指定结果图像的颜色模式或像素格式。如果没有提供,则模式将从输入数组的类型推断出来。

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

Example

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

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

Example

这是一个通过明确指定 mode 从 NumPy 数组创建 Pillow 图像的另一个示例。

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 bw

Example

此示例通过明确指定模式等于“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

Creating numpy array from a Pillow Image

numpy.asarray() 函数可用于将 Pillow 图像转换为 NumPy 数组。但是,在将 Pillow 图像转换为数组时值得注意的是,只有像素值被转移。这意味着某些图像模式(如 P 和 PA)在转换期间会丢失它们的调色板信息。

Example

以下示例演示如何将 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