5.1 Pillow 库概述
5.1.1 Pillow 简介与特点
Pillow 是 Python 图像库(PIL)的现代分支和继承者。PIL 最初由 Fredrik Lundh 于 1995 年开发,曾是 Python 最早的图像处理库之一。由于 PIL 在 2009 年后停止维护,Alex Clark 等人创建了 Pillow 项目,在保持向后兼容的同时持续更新。如今,Pillow 已成为 Python 生态中最流行的图像处理库,每月下载量巨大。
Pillow 的设计理念是简洁易用,提供直观的 API 和丰富的功能。与 OpenCV 相比,Pillow 更专注于图像的基本操作和格式处理,而非复杂的计算机视觉算法。它特别适合以下场景:文件读写、格式转换、基本几何变换(裁剪、缩放、旋转)、增强(滤镜、色彩调整)、绘制(文字、图形)以及元数据处理。
Pillow 支持超过 30 种图像格式,包括常见的 JPEG、PNG、GIF、BMP、TIFF、WebP,以及一些专业格式如 ICO、PPM 等。它对各种格式的读写进行了优化,允许设置压缩参数和质量。对于 GIF 支持动画,PNG 支持透明通道,JPEG 支持渐进式编码。
5.1.2 Pillow 与 OpenCV 的比较
Pillow 和 OpenCV 是 Python 图像处理领域的两大支柱,各有侧重。下表对比了它们的核心特性:
| 特性 | Pillow | OpenCV |
|---|---|---|
| 主要用途 | 图像处理、格式转换 | 计算机视觉、复杂处理 |
| 核心语言 | Python/C | C++ |
| 图像表示 | PIL.Image 对象 | NumPy 数组 |
| 格式支持 | 30+ 种 | 常见格式 |
| 学习曲线 | 简单易学 | 相对复杂 |
| 性能 | 中等 | 高 |
| 深度学习 | 需转换 | 直接支持 |
实际项目中常结合使用:用 Pillow 做读取和格式转换,用 OpenCV 做复杂算法。两者转换也很方便,Pillow 的 Image 对象可直接转为 NumPy 数组。
5.2 图像读取与写入
5.2.1 基本读写操作
Pillow 提供了简洁的 API 进行图像的读取和写入。Image.open() 用于读取文件,返回 Image 对象;Image.save() 用于保存,可根据扩展名自动识别格式。下面是一个封装好的 IO 类示例,展示了如何批量处理和保存不同格式:
""" Pillow 图像读写操作详解 演示各种图像格式的读取和写入方法 """
from PIL import Image, ExifTags
import numpy as np
import os
import io
class PillowImageIO:
SUPPORTED_FORMATS = {
'read': ['JPEG', 'PNG', 'GIF', 'BMP', , ],
: [, , , , , ]
}
():
() -> Image.Image:
:
Image.(file_path)
Exception e:
()
() -> :
:
output_dir = os.path.dirname(file_path)
output_dir os.path.exists(output_dir):
os.makedirs(output_dir, exist_ok=)
image.save(file_path, =, **kwargs)
Exception e:
()
() -> :
image = .open_image(input_path)
image :
.save_image(image, output_path, =output_format, **kwargs)
() -> :
os.path.exists(output_dir):
os.makedirs(output_dir, exist_ok=)
results = {: , : , : }
filename os.listdir(input_dir):
filename.lower().endswith((, , )):
input_file = os.path.join(input_dir, filename)
stem = os.path.splitext(filename)[]
output_file = os.path.join(output_dir, )
results[] +=
.convert_format(input_file, output_file):
results[] +=
:
results[] +=
results

