Python3 入门教程
图像处理:Pillow
本教程共 70 篇 · 第 65 篇 · 更新于 2026-07-22 · 约 3 分钟阅读
PythonPython3 入门教程Pillow图像处理批量处理
65. 图像处理:Pillow
本节目标:学会用 Pillow 打开、编辑和保存图片,掌握缩放、裁剪、旋转、加文字、加滤镜等常见操作。
Pillow 是 Python 图像处理的事实标准库。它从 PIL(Python Imaging Library) fork 而来,API 成熟稳定,功能覆盖日常图像处理的方方面面。
安装与打开图片
pip install pillow
from PIL import Image
img = Image.open('photo.jpg')
print(img.format, img.size, img.mode)
# 输出类似: JPEG (1920, 1080) RGB
format:图片格式,如 JPEG、PNG、GIF。size:宽和高的元组。mode:颜色模式,RGB真彩色,RGBA带透明通道,L灰度。
基本变换
缩放:
# 等比例缩放到宽度 800
ratio = 800 / img.size[0]
new_size = (800, int(img.size[1] * ratio))
thumb = img.resize(new_size, Image.Resampling.LANCZOS)
thumb.save('thumb.jpg', quality=90)
Image.Resampling.LANCZOS 是高质量的重采样滤镜,缩小图片时边缘更锐利。旧版 Pillow 用 Image.ANTIALIAS,新版已弃用。
裁剪:
# 从 (100, 100) 裁剪到 (400, 400)
cropped = img.crop((100, 100, 400, 400))
cropped.save('cropped.jpg')
crop() 的参数是四元组 (left, upper, right, lower)。
旋转和翻转:
rotated = img.rotate(45, expand=True) # expand=True 防止裁切
flipped = img.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
画图和加文字
Pillow 自带 ImageDraw 和 ImageFont 模块,可以在图片上画形状、写文字。
from PIL import ImageDraw, ImageFont
img = Image.open('photo.jpg')
draw = ImageDraw.Draw(img)
# 画矩形框
draw.rectangle((100, 100, 300, 300), outline='red', width=3)
# 画文字
try:
font = ImageFont.truetype('arial.ttf', 40)
except:
font = ImageFont.load_default()
draw.text((120, 120), 'Hello Pillow', fill='yellow', font=font)
img.save('annotated.jpg')
Tip中文字体需要指定系统里的中文字体文件,比如 Windows 上的
msyh.ttc(微软雅黑)、macOS 上的/System/Library/Fonts/PingFang.ttc。否则中文会显示成方框。
图像滤镜
Pillow 的 ImageFilter 提供了一批现成滤镜:
from PIL import ImageFilter
blurred = img.filter(ImageFilter.BLUR)
edges = img.filter(ImageFilter.FIND_EDGES)
sharpened = img.filter(ImageFilter.SHARPEN)
blurred.save('blurred.jpg')
格式转换与透明背景
把 PNG 的透明通道合成到白色背景上,再转成 JPEG:
if img.mode in ('RGBA', 'LA', 'P'):
background = Image.new('RGB', img.size, (255, 255, 255))
background.paste(img, mask=img.split()[-1] if img.mode != 'P' else None)
background.save('output.jpg', quality=95)
else:
img.save('output.jpg', quality=95)
批量处理图片
结合 pathlib 和 Pillow,可以批量处理一个文件夹里的所有图片:
from pathlib import Path
from PIL import Image
src_dir = Path('photos')
dst_dir = Path('thumbnails')
dst_dir.mkdir(exist_ok=True)
for img_path in src_dir.glob('*.jpg'):
img = Image.open(img_path)
img.thumbnail((300, 300))
img.save(dst_dir / img_path.name)
print(f"已处理: {img_path.name}")
thumbnail() 会原地修改图片,保持长宽比,不超过给定的尺寸。
小结
Image.open()打开图片,save()保存,size/mode/format查看元信息。resize()、crop()、rotate()、transpose()完成常见几何变换。ImageDraw和ImageFont在图片上画形状、写文字。ImageFilter提供模糊、锐化、边缘检测等滤镜效果。- 批量处理时配合
pathlib遍历文件夹,效率很高。
来源:参考了 liaoxuefeng「17.1. Pillow」、runoob「Python3 多线程」等,改写后所得。