图像处理 · 实战指南 · www.xservx.com
Python PIL库(Python Imaging Library)是Python生态中最经典、最成熟的图像处理开源项目。自1995年首次发布以来,它经历了多次迭代与重构。2011年,社区 fork 并更名为 Pillow,作为 PIL 的现代替代品,持续维护至今。Pillow 完全兼容 PIL 的 API,同时支持 Python 3.x,并新增了对现代图像格式(如 WebP、AVIF)的原生支持。它基于 C 语言底层优化,性能卓越,是图像处理、计算机视觉预处理、自动化图形生成等任务的首选工具。
在实际开发中,Python PIL库常被用于:
相较于其他图像库(如 OpenCV 偏向视频与算法、scikit-image 偏向科学计算),Python PIL库在 API 设计上更贴近开发者直觉,操作逻辑清晰,文档详尽,学习曲线平缓,是初学者入门图像处理的黄金起点。其模块化架构(Image、ImageFilter、ImageDraw、ImageFont、ImageOps 等)支持高度定制,满足从简单处理到复杂合成的全场景需求。
截至 2026 年,Pillow 在 PyPI 上的月下载量稳定超过 5000 万次,GitHub Stars 超 8000,社区活跃度常年位居图像处理类库前三。大量知名项目(如 Django CMS、Jupyter Notebook、Matplotlib 后端)均依赖其稳定能力。可以说,Python PIL库不仅是技术工具,更是图像工程领域的基础设施级存在。
安装 Python PIL库(即 Pillow)极其简便,官方推荐使用 pip 工具完成。以下为详细指南:
# 推荐:安装最新稳定版
pip install --upgrade pillow
若需指定版本(如兼容旧项目):
# 安装 Pillow 10.4.0(2026年主流稳定版)
pip install pillow==10.4.0
验证安装是否成功:
python -c "from PIL import Image; print(Image.__version__)"
预期输出类似:10.4.0。若报错 No module named 'PIL',请检查 Python 环境路径或权限设置。
使用系统级 Python 时易遇此问题。解决方案:
pip install --user pillowpython -m venv venv && source venv/bin/activate && pip install pillow部分图像格式依赖系统库。Ubuntu/Debian 用户可预装:
sudo apt update && sudo apt install -y libjpeg-dev zlib1g-dev libtiff-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev libpython3-dev
避免手动编译!Pillow 官方提供预编译 wheel 包(.whl)。确保 pip ≥ 21.0,直接安装即可自动匹配平台包。
Python PIL库的核心功能由三大模块支撑,下文以实战代码展开说明:
Image 类是所有操作的起点。关键方法如下:
| 方法 | 功能说明 | 典型参数 |
|---|---|---|
Image.open(path) |
加载图像文件 | 路径、文件对象、bytes |
img.resize((w, h)) |
调整尺寸 | 新尺寸元组、重采样算法(NEAREST/BILINEAR/ bicubic/LANCZOS) |
img.rotate(angle) |
旋转图像 | 角度、是否扩展画布(expand=True) |
img.save(path) |
保存图像 | 路径、格式(JPEG/PNG/WebP) |
img.crop(box) |
裁剪区域 | 左上右下坐标元组 (left, upper, right, lower) |
用于在图像上添加几何图形、文字等元素:
from PIL import Image, ImageDraw
# 创建空白画布
img = Image.new('RGB', (400, 300), color='white')
draw = ImageDraw.Draw(img)
# 绘制矩形
draw.rectangle([50, 50, 350, 250], outline='blue', width=3)
# 绘制圆形
draw.ellipse([100, 100, 300, 200], fill='#ffcc00', outline='red')
# 绘制文字(需先加载字体)
font = ImageFont.truetype('Arial.ttf', 24)
draw.text((120, 140), 'Hello PIL!', font=font, fill='black')
img.save('draw_example.png')
关键注意点:
Image.new(mode, size, color) 中 mode 常用 'RGB'(彩色)、'L'(灰度)、'RGBA'(带透明通道)ImageFont.truetype() 加载字体文件,否则回退到默认字体(效果不可控)提供预设滤镜,支持快速应用模糊、锐化等效果:
| 滤镜 | 效果 | 适用场景 |
|---|---|---|
BLUR |
均值模糊 | 背景虚化、降噪预处理 |
CONTOUR |
轮廓提取 | 边缘检测、素描风格生成 |
SHARPEN |
锐化 | 模糊图像增强细节 |
EDGE_ENHANCE |
边缘增强 | 图像清晰度提升 |
from PIL import Image, ImageFilter
img = Image.open('photo.jpg')
# 应用高斯模糊(标准差=2)
blurred = img.filter(ImageFilter.GaussianBlur(radius=2))
# 应用边缘增强
enhanced = img.filter(ImageFilter.EDGE_ENHANCE)
enhanced.save('enhanced.jpg')
图像格式选择直接影响文件体积与画质。以下是 Python PIL库 支持的主流格式对比与转换技巧:
| 格式 | 有损/无损 | 透明通道 | 适用场景 | 推荐质量参数 |
|---|---|---|---|---|
| JPEG | 有损 | 不支持 | 照片、复杂渐变图 | quality=85 (平衡体积与画质) |
| PNG | 无损 | 支持(Alpha) | 图标、透明背景图、简单图形 | compression_level=6 (默认) |
| WebP | 有损/无损 | 支持 | Web 优化、现代浏览器 | quality=75, method=6 |
| AVIF | 有损/无损 | 支持 | 高画质压缩、未来趋势 | quality=50 (同等画质下比 WebP 更小) |
import os
from PIL import Image
def convert_to_webp(source_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
for filename in os.listdir(source_dir):
if filename.lower().endswith(('.jpg', '.jpeg', '.png')):
img_path = os.path.join(source_dir, filename)
img = Image.open(img_path)
# 转换为RGB(避免RGBA转JPEG报错)
if img.mode in ('RGBA', 'P'):
img = img.convert('RGB')
# 保存为WebP
output_path = os.path.join(output_dir, os.path.splitext(filename)[0] + '.webp')
img.save(output_path, 'webp', quality=80, method=6)
print(f"Converted: {filename} → {os.path.basename(output_path)}")
convert_to_webp('input_images', 'output_webp')
Python PIL库的滤镜系统不仅限于基础效果,还可组合实现复杂视觉处理:
通过 ImageFilter.Kernel 实现自定义卷积核,例如锐化与浮雕效果:
from PIL import Image, ImageFilter
# 锐化卷积核
sharpen_kernel = ImageFilter.Kernel((3, 3),
[0, -1, 0, -1, 5, -1, 0, -1, 0],
scale=None, offset=0)
# 浮雕卷积核
emboss_kernel = ImageFilter.Kernel((3, 3),
[-2, -1, 0, -1, 1, 1, 0, 1, 2],
scale=1, offset=128)
img = Image.open('portrait.jpg')
sharpened = img.filter(sharpen_kernel)
embossed = img.filter(emboss_kernel)
sharpened.save('sharpened.jpg')
embossed.save('embossed.jpg')
组合使用滤镜与图像运算,可生成近似手绘效果:
from PIL import Image, ImageFilter, ImageOps
def sketch_effect(image_path, output_path):
# 1. 转灰度
img = Image.open(image_path).convert('L')
# 2. 反相(负片)
inverted = ImageOps.invert(img)
# 3. 高斯模糊
blurred = inverted.filter(ImageFilter.GaussianBlur(radius=2))
# 4. 颜色 dodge 混合(模拟素描)
result = Image.blend(img, blurred, alpha=0.5)
result.save(output_path)
sketch_effect('input.jpg', 'sketch_output.jpg')
Pillow 3.0 引入 ImageFilter.BLUR 的 radius 参数,支持可控模糊强度
新增 ImageFilter.BoxBlur(快速盒模糊),性能优于传统高斯模糊
支持 WebP 动图(.webp),可处理动画滤镜序列
AVIF 格式支持成熟,滤镜处理效率提升 40%
文字是信息图、海报、水印的核心元素。Python PIL库 提供精细的文字控制能力:
支持 TrueType(.ttf)和 OpenType(.otf)字体,关键参数:
| 参数 | 说明 | 推荐值 |
|---|---|---|
font_path |
字体文件路径 | 系统字体(如 /usr/share/fonts/...)或自定义字体 |
size |
字号(像素) | 12~72(根据画布尺寸调整) |
encoding |
编码格式 | 'unic'(支持 Unicode 全字符集) |
原生不支持自动换行,需自定义函数:
def draw_multiline_text(draw, text, position, font, max_width):
words = text.split()
lines = []
current_line = words[0]
for word in words[1:]:
test_line = current_line + ' ' + word
if draw.textbbox((0, 0), test_line, font=font)[2] <= max_width:
current_line = test_line
else:
lines.append(current_line)
current_line = word
lines.append(current_line)
y = position[1]
for line in lines:
draw.text((position[0], y), line, font=font, fill='black')
y += font.getbbox(line)[3] - font.getbbox(line)[1] + 6
# 使用示例
img = Image.new('RGB', (500, 200), 'white')
draw = ImageDraw.Draw(img)
font = ImageFont.truetype('SimHei.ttf', 20)
text = "这是一个超长文本,需要自动换行处理以适应指定宽度"
draw_multiline_text(draw, text, (20, 30), font, max_width=460)
img.save('multiline.png')
增强文字可读性,尤其在复杂背景上:
def draw_text_with_shadow(draw, text, position, font, text_color, shadow_color):
# 绘制阴影
draw.text((position[0]+2, position[1]+2), text, font=font, fill=shadow_color)
# 绘制主文字
draw.text(position, text, font=font, fill=text_color)
img = Image.new('RGB', (400, 150), '#037ef3')
draw = ImageDraw.Draw(img)
font = ImageFont.truetype('Arial.ttf', 32)
draw_text_with_shadow(draw, 'Python PIL', (50, 50), font, 'white', 'rgba(0,0,0,0.3)')
img.save('shadow_text.png')
Python PIL库添加水印的标准流程:加载底图与水印图 → 调整水印透明度 → 合成图像。
from PIL import Image, ImageEnhance
def add_watermark(base_path, watermark_path, output_path, opacity=0.3):
base = Image.open(base_path).convert('RGBA')
watermark = Image.open(watermark_path).convert('RGBA')
# 调整水印透明度
alpha = int(255 * opacity)
r, g, b, a = watermark.split()
a = a.point(lambda x: x * opacity)
watermark = Image.merge('RGBA', (r, g, b, a))
# 合成(左上角)
base.paste(watermark, (10, 10), watermark)
base.save(output_path)
add_watermark('photo.jpg', 'logo.png', 'watermarked.jpg')
处理 PNG 透明背景的关键是保留 Alpha 通道:
save(..., format='PNG'),避免转为 JPEGimg = img.convert('RGBA')paste(mask=alpha_channel) 保留透明区域img = Image.open('transparent.png').convert('RGBA')
# 在透明背景上绘制半透明矩形
draw = ImageDraw.Draw(img)
draw.rectangle([50, 50, 200, 150], fill=(255, 0, 0, 128))
img.save('with_shape.png')
验证码生成需包含:随机字符、扭曲、干扰线、噪点。
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
def generate_captcha(width=160, height=60):
img = Image.new('RGB', (width, height), color='white')
draw = ImageDraw.Draw(img)
font = ImageFont.truetype('Arial.ttf', 40)
# 生成4位随机字符
chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
text = ''.join(random.choices(chars, k=4))
# 绘制字符(带旋转)
x = 10
for i, char in enumerate(text):
angle = random.randint(-15, 15)
char_img = Image.new('RGBA', (40, 50), (0,0,0,0))
c_draw = ImageDraw.Draw(char_img)
c_draw.text((0,0), char, font=font, fill='black')
rotated = char_img.rotate(angle, expand=True)
img.paste(rotated, (x, 5), rotated)
x += 35
# 添加干扰线
for _ in range(5):
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
draw.line([(x1,y1), (x2,y2)], fill='gray', width=2)
# 添加噪点
pixels = img.load()
for _ in range(100):
pixels[random.randint(0, width-1), random.randint(0, height-1)] = (
random.randint(0,255), random.randint(0,255), random.randint(0,255)
)
return img, text
captcha_img, captcha_text = generate_captcha()
captcha_img.save('captcha.png')
print(f"验证码文本: {captcha_text}")
批量处理建议使用 pathlib 遍历目录:
from pathlib import Path
from PIL import Image
def batch_process(input_dir, output_dir, target_size=(800, 600)):
input_dir = Path(input_dir)
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
for img_path in input_dir.glob('*.{jpg,jpeg,png}'):
try:
img = Image.open(img_path)
# 等比例缩放
img.thumbnail(target_size, Image.Resampling.LANCZOS)
# 保存为JPEG(移除Alpha通道)
if img.mode == 'RGBA':
img = img.convert('RGB')
output_path = output_dir / f"{img_path.stem}_resized.jpg"
img.save(output_path, 'JPEG', quality=90)
print(f"处理完成: {img_path.name}")
except Exception as e:
print(f"跳过 {img_path.name}: {e}")
batch_process('input_images', 'output_resized')