Python Pillow库详细介绍与代码示例
目录
- 一、Pillow 库简介
- 二、安装 Pillow
- 三、核心功能及代码示例
- 1. 打开/保存图像
- 2. 基本图像操作
- 3. 图像处理
- 4. 绘制图形和文字
- 5. 高级操作
- 四、综合应用示例:添加水印
- 五、注意事项
- 六、典型应用场景
- 七、高级图像处理技巧
- 1. 通道操作与混合
- 2. 颜色空间转换
- 3. EXIF 元数据处理
- 八、性能优化技巧
- 1. 大图处理方案
- 2. 使用内存优化模式
- 3. 加速像素操作
- 九、实战项目示例
- 1. 生成验证码图片
- 2. 批量图片处理器
- 十、图像分析功能
- 1. 直方图分析
- 2. 边缘检测
- 十一、错误处理与调试
- 1. 健壮的图像处理
- 2. 内存管理技巧
- 十二、与其他库集成
- 1. 结合 OpenCV 使用
- 2. 结合 Matplotlib 显示
- 十三、扩展知识
- 1. 自定义滤镜
- 2. 插件图像格式支持
- 十四、最佳实践建议
- 十五、高级图像分析技术
- 1. 直方图匹配(色调映射)
- 2. 图像分割(阈值处理)
- 十六、专业领域应用
- 1. 医学影像处理(DICOM)
- 2. 卫星图像处理(多光谱分析)
- 十七、三维图像处理
- 1. Z-Stack 图像合成
- 十八、GPU加速处理
- 1. 使用 CUDA 加速(需安装 cupy)
- 十九、与深度学习框架集成
- 1. PyTorch 数据增强管道
- 二十、插件开发与扩展
- 1. 自定义图像格式解码器
- 2. 编写滤镜插件
- 二十一、工程化实践
- 1. 图像处理微服务架构
- 2. 自动化测试框架
- 二十二、前沿应用案例
- 1. AI 艺术风格迁移
- 2. 动态二维码生成
- 二十三、调试与性能分析
- 1. 内存分析工具
- 2. 性能剖析
- 二十四、跨平台开发注意事项
- 二十五、资源与进阶学习
一、Pillow 库简介
- 功能:图像打开/保存、尺寸调整、滤镜应用、颜色处理、绘图、文字添加等
- 支持格式:JPEG, PNG, GIF, BMP, TIFF 等 30+ 格式
- 核心模块:Image, ImageDraw, ImageFilter, ImageEnhance 等
二、安装 Pillow
pip install Pillow
三、核心功能及代码示例
1. 打开/保存图像
from PIL import Image # 打开图像 img = Image.open("input.jpg") print(f"格式: {img.format}, 尺寸: {img.size}, 模式: {img.mode}") # 保存图像(自动识别格式) img.save("output.png") # 转换格式 img.save("converted.webp", "WEBP")
2. 基本图像操作
# 调整尺寸 resized = img.resize((300, 200)) # 旋转(expand参数防止裁剪) rotated = img.rotate(45, expand=True) # 裁剪 (left, upper, right, lower) cropped = img.crop((100, 100, 400, 400)) # 缩略图生成(保持比例) img.thumbnail((128, 128)) img.save("thumbnail.jpg")
3. 图像处理
from PIL import ImageFilter, ImageEnhance # 应用滤镜 blurred = img.filter(ImageFilter.GaussianBlur(radius=2)) contour = img.filter(ImageFilter.CONTOUR) # 颜色调整 gray = img.convert("L") # 转为灰度 enhancer = ImageEnhance.Contrast(img) contrast_img = enhancer.enhance(2.0) # 对比度增强2倍 # 调整亮度 bright_enhancer = ImageEnhance.Brightness(img) bright_img = bright_enhancer.enhance(1.5)
4. 绘制图形和文字
from PIL import ImageDraw, ImageFont # 创建新画布 canvas = Image.new("RGB", (500, 500), color=(255, 255, 255)) draw = ImageDraw.Draw(canvas) # 绘制形状 draw.rectangle([50, 50, 200, 200], fill="red", outline="blue") draw.ellipse([250, 250, 400, 400], fill="yellow") # 添加文字 try: font = ImageFont.truetype("arial.ttf", 24) except IOError: font = ImageFont.load_default() draw.text((100, 300), "Hello Pillow!", fill="black", font=font) canvas.show()
5. 高级操作
# 图像合成 overlay = Image.new("RGBA", img.size, (255, 0, 0, 100)) composite = Image.alpha_composite(img.convert("RGBA"),bYpvufDA overlay) # 像素级操作 pixels = img.load() for y in range(img.height): for x in range(img.width): r, g, b = pixels[x, y] pixels[x, y] = (r//2, g//2, b//2) # 暗化效果 # 创建 GIF images = [img, rotated, cropped] images[0].save("animation.gif", save_all=True, append_images=images[1:], duration=500, loop=0)
四、综合应用示例:添加水印
def add_watermark(input_path, output_path, text): base = Image.open(input_path).convert("RGBA") txt = Image.new("RGBA", base.size, (255,255,255,0)) draw = ImageDraw.Draw(txt) font = ImageFont.truetype("arial.ttf", 36) # 计算文字位置 text_width, text_height = draw.textsize(text, font) x = base.width - text_width - 10 y = base.height - text_height - 10 draw.text((x, y), text, font=font, fill=(255,255,255,128)) combined = Image.alpha_composite(base, txt) combined.convert("RGB").save(output_path) add_watermark("photo.jpg", "watermarked.jpg", " Your Brand")
五、注意事项
- 处理透明通道时使用
RGBA
模式 - JPEG 格式不支持透明度,保存时需转换模式
- 大尺寸图像处理需注意内存消耗
- 使用
with
语句管理文件资源:
with Image.open("large_image.tiff") as img: # 处理图像
六、典型应用场景
- 批量生成缩略图
- 为图片添加版权信息
- 图像格式转换工具
- 创建动态验证码图片
- 图像数据增强(机器学习)
七、高级图像处理技巧
1. 通道操作与混合
from PIL import Image, ImageChops # 分离 RGB 通道 r, g, b = img.split() # 合并时调整通道顺序(例如创建伪红外效果) modified = Image.merge("RGB", (b, g, r)) # 通道混合(数学运算) diff = ImageChops.difference(img1, img2) # 像素差异图 blended = ImageChops.blend(img1, img2, alpha=0.3) # 图像叠加
2. 颜色空间转换
# CMYK 转 RGB cmyk_img = Image.open("cmyk_image.tiff").convert("RGB") # 转换为 HSV 颜色空间(需使用第三方库补充) # 注意:Pillow 原生不支持 HSV 操作,但可通过 numpy 实现 import numpy as np hsv_array = np.array(img.convert("HSV")) # ...处理 HSV 数组... modified_img = Image.fromarray(hsv_array, "HSV").convert("RGB")
3. EXIF 元数据处理
# 读取 EXIF 数据 exif_data = img._getexif() if exif_data: from PIL.ExifTags import TAGS for tag_id, value in exif_data.items(): tag_name = TAGS.get(tag_id, tag_id) print(f"{tag_name}: {value}") # 旋转图像(根据 EXIF 方向信息自动修正) from PIL import ImageOps fixed_img = ImageOps.exif_transpose(img)
八、性能优化技巧
1. 大图处理方案
# 分块处理大图 tile_size = 512 for y in range(0, img.height, tile_size): for x in range(0, img.width, tile_size): box = (x, y, x+tile_size, y+tile_size) tile = img.crop(box) # 处理分块... img.paste(tile, box)
2. 使用内存优化模式
# 使用 LA 模式替代 RGBA(节省 25% 内存) gray_alpha = img.convert("LA")
3. 加速像素操作
# 使用 numpy 加速像素处理 import numpy as np arr = np.array(img) arr = arr // 2 # 快速暗化处理 fast_processed = Image.fromarray(arr)
九、实战项目示例
1. 生成验证码图片
from PIL import Image, ImageDraw, ImageFont, ImageFilter import random def generate_captcha(text, size=(200, 80)): img = Image.new("RGB", size, (255,255,255)) draw = ImageDraw.Draw(img) # 绘制干扰线 for _ in range(8): start = (random.randint(0, size[0]), random.randint(0, size[1])) end = (random.randint(0, size[0]), random.randint(0, size[1])) draw.line([start, end], fill=(random.randint(0,255), random.randint(0,255), random.randint(0,255)), width=2) # 添加文字 font = ImageFont.truetype("arial.ttf", 36) text_width, text_height = draw.textbbox((0,0), text, font=font)[2:] x = (size[0] - text_width) / 2 y = (size[1] - text_height) / 2 # 文字扭曲 for i, char in enumerate(text): draw.text( (x + i*30 + random.randint(-5,5), y + random.randint(-5,5)), char, font=font, fill=(random.randint(0,160), random.randint(0,160), random.randint(0,160)) ) # 添加滤镜 img = img.filter(ImageFilter.SMOOTH_MORE) return img captcha = generate_captcha("3A4B") captcha.save("captcha.jpg"http://www.devze.com)
2. 批量图片处理器
import os from PIL import Image, ImageOps def BATch_process(input_dir, output_dir, process_func): os.makedirs(output_dir, exist_ok=True) for filename in os.listdir(input_dir): if filename.lower().split('.')[-1] not in ['jpg', 'png', 'jpeg']: continue with Image.open(os.path.join(input_dir, filename)) as img: processed = process_func(img) processed.save(os.path.join(output_dir, filename)) # 示例处理函数:转换为素描风格 def sketch_effect(img): gray = img.convert("L") invert = ImageOps.invert(gray) blur = invert.filter(ImageFilter.GaussianBlur(3)) return ImageChops.dodge(gray, blur) batch_process("./photos", "./processed", sketch_effect)
十、图像分析功能
1. 直方图分析
histogram = img.histogram() # 获取 R 通道直方图(前256个值) red_hist = histogram[:256] # 绘制简易直方图(需 matplotlib) import matplotlib.pyplot as plt plt.figure(figsize=(10,4)) plt.title("Red Channel Histogram") plt.bar(range(256), red_hist, color='red') plt.show()
2. 边缘检测
from PIL import ImageFilter edges = img.convert("L").filter(ImageFilter.FIND_EDGES) edges = edges.point(lambda x: 255 if x > 50 else 0) # 二值化 edges.show()
十一、错误处理与调试
1. 健壮的图像处理
try: with Image.open("problematic.jpg") as img: # 处理图像... except IOError as e: print(f"无法打开图像文件: {str(e)}") except Image.DecompressionBombError: print("图像尺寸过大,请检查是否安全!")
2. 内存管理技巧
# 强制释放图像内存 img.close() # 显式关闭 # 使用 with 语句自动管理 with Image.open("large_image.tiff") as img: thumbnail = img.copy() thumbnail.thumbnail((1024, 1024)) thumbnail.save("small.jpg") # 注意:此时原图已关闭
十二、与其他库集成
1. 结合 OpenCV 使用
import cv2 import numpy as np from PIL import Image # Pillow -> OpenCV pil_img = Image.open("demo.jpg") cv_img = np.array(pil_img.convert('RGB'))[:, :, ::-1] # RGB to BGR # OpenCV -> Pillow cv_img = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB) pil_img = Image.fromarray(cv_img)
2. 结合 Matplotlib 显示
import matplotlib.pyplot as plt plt.imshow(img) plt.axis('off') plt.title("Pillow Image Display") plt.show()
十三、扩展知识
1. 自定义滤镜
from PIL import ImageFilter class CustomFilter(ImageFilter.BuiltinFilter): name = "CustomSharpen" filterargs = (3, 3), 16, 0, ( -1, -1, -1, -1, 24, -1, -1, -1, -1 ) sharpewww.devze.comned = img.filter(CustomFilter())
2. 插件图像格式支持
# 安装额外解码器后,可支持 WebP 动画等 # 需安装:pip install pillow-heif import pillow_heif heif_file = pillow_heif.open_heif("image.heif") heif_img = Image.frombytes( heif_file.mode, heif_file.size, heif_file.data, "raw", heif_file.mode, heif_file.stride, )
十四、最佳实践建议
格式选择策略
- 网页使用:
JPEG
(照片)、PNG
(透明/图标)、WEBP
(现代格式) - 打印使用:
TIFF
(无损)、PDF
(矢量) - 动态图片:
GIF
(简单动画)、APNG
(高质量动画)
- 网页使用:
质量参数优化
img.save("optimized.jpg", quality=85, # 质量值 (1-100) optimize=True, # 启用优化 progressive=True) # 渐进式JPEG
- 多帧图像处理(GIF/TIFF)
with Image.open("animation.gif") as img: for frame in ImageSequence.Iterator(img): # 处理每一帧 frame.save(f"frame_{frame.tell()}.png")
十五、高级图像分析技术
1. 直方图匹配(色调映射)
import numpy as np from PIL import Image def histogram_matching(source, template): """ 将源图像的直方图匹配到模板图像 """ src = np.array(source.convert('L')).flatten() tgt = np.array(template.convert('L')).flatten() # 计算累积分布函数 src_vals, src_counts = np.unique(src, return_counts=True) tgt_vals, tgt_counts = np.unique(tgt, return_counts=True) src_cdf = np.cumsum(src_counts) / src.size tgt_cdf = np.cumsum(tgt_counts) / tgt.size # 创建映射表 lut = np.interp(src_cdf, tgt_cdf, tgt_vals) return source.point(lut) source_img = Image.open("landscape.jpg") template_img = Image.open("sunset.jpg") matched = histogram_matching(source_img, template_img)
2. 图像分割(阈值处理)
from PIL import ImageOps # Otsu 自动阈值算法 gray = img.convert('L') thresh = gray.point(lambda x: 255 if x > 130 else 0) # 手动阈值 # 自动阈值(需要 scikit-image) from skimage.filters import threshold_otsu arr = np.array(gray) thresh_val = threshold_otsu(arr) auto_thresh = Image.fromarray((arr > thresh_val).astype(np.uint8) * 255)
十六、专业领域应用
1. 医学影像处理(DICOM)
# 需要安装 pydicom import pydicom from PIL import Image ds = pydicom.dcmread("MRI.dcm") arr = ds.pixel_array.astype(float) arr = (arr - arr.min()) / (arr.max() - arr.min()) * 255 medical_img = Image.fromarray(arr.astype(np.uint8)) medical_img.save("mri_preview.png")
2. 卫星图像处理(多光谱分析)
# 加载多波段图像 with Image.open("satellite.tif") as img: bands = [img.getchannel(band) for band in ('R', 'G', 'B', 'NIR')] # 计算 NDVI(归一化植被指数) red = np.array(bands[0], dtype=np.float32) nir = np.array(bands[3], dtype=np.float32) ndvi = (nir - red) / (nir + red + 1e-10) # 防止除以零 # 可视化 NDVI ndvi_img = Image.fromarray(np.uint8((ndvi + 1) * 127.5)) ndvi_img.save("ndvi_map.png")
十七、三维图像处理
1. Z-Stack 图像合成
importphp glob from PIL import Image, ImageMath # 加载聚焦堆栈图像 z_images = [Image.open(f) for f in sorted(glob.glob("z_stack_*.tif"))] # 创建全聚焦图像 def focus_metric(pixels): return np.std(pixels) # 使用标准差作为清晰度指标 depth_map = np.zeros(z_images[0].size[::-1]) final_img = np.zeros_like(np.array(z_images[0])) for i in range(z_images[0].height): for j in range(z_images[0].width): pixels = [np.array(img)[i,j] for img in z_images] sharpness = [focus_metric(p) for p in pixels] best_idx = np.argmax(sharpness) final_img[i,j] = pixels[best_idx] depth_map[i,j] = best_idx Image.fromarray(final_img).save("focused.tif") Image.fromarray(np.uint8(depth_map * 255 / len(z_images))).save("depth_map.png")
十八、GPU加速处理
1. 使用 CUDA 加速(需安装 cupy)
import cupy as cp from PIL import Image def gpu_filter(img): # 转换到 GPU img_gpu = cp.asarray(img) # 自定义核函数(边缘检测) kernel = cp.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], dtype=cp.float32) # 卷积运算 filtered = cp.zeros_like(img_gpu) for c in range(3): filtered[:, :, c] = cp.convolve2d(img_gpu[:, :, c], kernel, mode='same') # 返回 CPU return Image.fromarray(cp.asnumpy(filtered).astype(np.uint8)) original = Image.open("gpu_demo.jpg") accelerated = gpu_filter(original)
十九、与深度学习框架集成
1. PyTorch 数据增强管道
from torchvision import transforms from PIL import Image class AdvancedAugmentation: def __init__(self): self.transform = transforms.Compose([编程客栈 transforms.RandomApply([ lambda x: transforms.functional.adjust_sharpness(x, 2), lambda x: ImageEnhance.Color(x).enhance(0.8) ], p=0.5), transforms.RandomPerspective(distortion_scale=0.3), transforms.ColorJitter(brightness=0.2, contrast=0.2) ]) def __call__(self, img): return self.transform(img) augmenter = AdvancedAugmentation() img = Image.open("training_sample.jpg") augmented = augmenter(img)
二十、插件开发与扩展
1. 自定义图像格式解码器
from PIL import Image, ImageFile class RAWDecoder(ImageFile.PyDecoder): def decode(self, buffer): # 实现自定义 RAW 格式解析 raw_data = self._parse_custom_format(buffer) self.set_as_raw(bytes(raw_data)) return -1, 0 # 注册解码器 Image.register_decoder("MYRAW", RAWDecoder) Image.register_extensions("MYRAW", [".raw"])
2. 编写滤镜插件
from PIL import ImageFilter class KaleiDOScopeFilter(ImageFilter.BuiltinFilter): name = "Kaleidoscope" filterargs = (5, 5), 16, 0, ( 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1 ) img.filter(KaleidoscopeFilter()).show()
二十一、工程化实践
1. 图像处理微服务架构
# 使用 FastAPI 构建 REST API from fastapi import FastAPI, File, UploadFile from PIL import Image import io app = FastAPI() @app.post("/enhance") async def enhance_image(file: UploadFile = File(...)): img = Image.open(io.BytesIO(await file.read())) # 执行处理管线 enhanced = (img.convert('RGB') .filter(ImageFilter.SHARPEN) .enhance(contrast=1.2) .resize((1024, 768))) byte_arr = io.BytesIO() enhanced.save(byte_arr, format='JPEG') return Response(content=byte_arr.getvalue(), media_type="image/jpeg")
2. 自动化测试框架
import unittest from PIL import Image, ImageChops class ImageTests(unittest.TestCase): def test_watermark(self): original = Image.new('RGB', (800, 600), 'white') watermarked = add_watermark(original.copy(), "Test") # 验证水印位置和内容 diff = ImageChops.difference(original, watermarked) self.assertGreater(diff.getbbox()[2], 700) # 检查右下角变化 def test_performance(self): large_img = Image.new('RGB', (10000, 10000)) start = time.time() large_img.thumbnail((1000, 1000)) self.assertLess(time.time() - start, 1.0)
二十二、前沿应用案例
1. AI 艺术风格迁移
# 结合 Pillow 与深度学习模型 def style_transfer(content_img, style_img): # 加载预训练模型(需安装 torch 和 torchvision) from torchvision.models import vgg19 model = vgg19(pretrained=True).features.eval() # 特征提取与风格迁移算法... # (此处实现具体迁移逻辑) return Image.fromarray(output) content = Image.open("photo.jpg") style = Image.open("starry_night.jpg") artwork = style_transfer(content, style)
2. 动态二维码生成
from PIL import Image, ImageDraw import qrcode def animated_qr(data, logo_path): base = qrcode.make(data).convert('RGBA') logo = Image.open(logo_path).resize((100, 100)) frames = [] for angle in range(0, 360, 30): rotated_logo = logo.rotate(angle) frame = base.copy() frame.alpha_composite(rotated_logo, ((frame.width-100)//2, (frame.height-100)//2)) frames.append(frame) frames[0].save("qr_animation.gif", save_all=True, append_images=frames[1:], duration=200, loop=0, optimize=True)
二十三、调试与性能分析
1. 内存分析工具
import tracemalloc from PIL import Image tracemalloc.start() # 测试代码块 with Image.open("large.tiff") as img: processed = img.resize((2000, 2000)) processed.save("output.jpg") snapshot = tracemalloc.take_snapshot() top_stats = snapshot.statistics('lineno') print("[ 内存消耗 Top 10 ]") for stat in top_stats[:10]: print(stat)
2. 性能剖析
# 使用 cProfile 分析处理流程 python -m cProfile -s cumulative image_processor.py
二十四、跨平台开发注意事项
- 字体处理兼容性
# 安全字体加载方案 def safe_font_loading(font_path, fallback_size=20): try: return ImageFont.truetype(font_path, size=fallback_size) except IOError: print(f"字体 {font_path} 加载失败,使用系统默认字体") return ImageFont.load_default()
- 路径处理规范
from pathlib import Path input_path = Path("input_images") / "special_chars_测试.jpg" output_path = input_path.with_name(f"processed_{input_path.name}")
二十五、资源与进阶学习
官方文档扩展阅读
- 高级图像变换:
Image.transform()
方法 - 分块编码器:
JpegEncoder
和WebPEncoder
- 图像协议:支持
HTTP
、FTP
等协议直接读取
- 高级图像变换:
通过掌握这些高级技术,将能够:
- 处理专业领域的图像分析需求
- 构建企业级图像处理系统
- 优化处理流程达到工业级性能
- 开发自定义图像处理扩展
- 集成 Pillow 到现代 AI 工作流
建议实践方向:开发智能相册管理系统、创建医学影像分析工具、构建云端图像处理 API 服务,或实现实时视频帧处理管道。持续关注 Pillow 的 github 仓库(https://github.com/python-pillow/Pillow)获取最新功能更新。
以上就是Python Pillow库详细介绍与代码示例的详细内容,更多关于Python Pillow库介绍的资料请关注编程客栈(www.devze.com)其它相关文章!
精彩评论