Python Pillow 库详解文档(最新推荐)

2025-06-21 16:50

本文主要是介绍Python Pillow 库详解文档(最新推荐),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《PythonPillow库详解文档(最新推荐)》Pillow是Python中最流行的图像处理库,它是PythonImagingLibrary(PIL)的现代分支和继承者,本文给大家介绍Pytho...

Python Pillow 库详解文档

简介

Pillow (PIL Fork) 是 Python 中最流行的图像处理库,它是 Python Imaging Library (PIL) 的现代分支和继承者。Pillow 提供了广泛的图像处理功能,支持多种图像格式的读取、处理、保存和显示。

安装

pip install Pillow

核心模块架构

Pillow 库的核心围绕 Image 类构建,同时提供了多个专门的子模块来处理不同的图像处理任务。主要的模块包括图像基础操作、滤镜处理、颜色管理、字体渲染、图像增强等功能模块。

Image 模块 - 核心图像处理

基本导入和使用

from PIL import Image, ImageDraw, ImageFont
import os

图像创建与打开

创建新图像

# 创建空白图像
img = Image.new('RGB', (800, 600), color='white')
img = Image.new('RGBA', (400, 300), color=(255, 0, 0, 128))
# 创建渐变图像
img = Image.new('L', (256, 256))
for x in range(256):
    for y in range(256):
        img.putpixel((x, y), x)

打开现有图像

# 打开图像文件
img = Image.open('example.jpg')
img = Image.open('path/to/image.png')
# 验证图像
try:
    img.verify()
    print("图像文件有效")
except:
    print("图像文件损坏")

图像基本属性和信息

# 获取图像基本信息
print(f"尺寸: {img.size}")  # (width, height)
print(f"模式: {img.mode}")  # RGB, RGBA, L, P 等
print(f"格式: {img.format}")  # JPEG, PNG, GIF 等
print(f"调色板: {img.palette}")
# 获取图像统计信息
extrema = img.getextrema()  # 最小值和最大值
histogram = img.histogram()  # 直方图数据

图像变换操作

尺寸调整

# 调整图像大小
resized = img.resize((400, 300))  # 指定尺寸
resized = img.resize((400, 300), Image.LANCZOS)  # 指定重采样算法
# 按比例缩放
width, height = img.size
new_img = img.resize((width//2, height//2))
# 创建缩略图
img.thumbnail((128, 128))  # 保持宽高比

旋转和翻转

# 旋转图像
rotated = img.rotate(45)  # 顺时针旋转45度
rotated = img.rotate(90, expand=True)  # 扩展画布适应旋转
# 翻转图像
flipped_h = img.transpowww.chinasem.cnse(Image.FLIP_LEFT_RIGHT)  # 水平翻转
flipped_v = img.transpose(Image.FLIP_TOP_BOTTOM)  # 垂直翻转
rotated_90 = img.transpose(Image.ROTATE_90)  # 90度旋转

裁剪操作

# 矩形裁剪
box = (100, 100, 400, 300)  # (left, top, right, bottom)
cropped = img.crop(box)
# 智能裁剪到内容边界
bbox = img.getbbox()
if bbox:
    trimmed = img.crop(bbox)

图像模式转换

# 模式转换
gray_img = img.convert('L')  # 转为编程灰度
rgba_img = img.convert('RGBA')  # 添加透明通道
rgb_img = img.convert('RGB')  # 移除透明通道
# 带抖动的转换
palette_img = img.convert('P', dither=Image.FLOYDSTEINBERG)

ImageDraw 模块 - 图形绘制

ImageDraw 模块提供了在图像上绘制各种图形和文本的功能。

基础绘制操作

from PIL import Image, ImageDraw
# 创建绘制对象
img = Image.new('RGB', (400, 300), 'white')
draw = ImageDraw.Draw(img)
# 绘制基本形状
draw.rectangle([50, 50, 150, 100], fill='red', outline='black', width=2)
draw.ellipse([200, 50, 350, 150], fill='blue', outline='navy')
draw.line([0, 0, 400, 300], fill='green', width=3)
# 绘制多边形
points = [(100, 200), (150, 250), (200, 200), (175, 150), (125, 150)]
draw.polygon(points, fill='yellow', outline='orange')

文本绘制

# 基础文本绘制
draw.text((50, 200), "Hello World", fill='black')
# 使用自定义字体
try:
    font = ImageFont.truetype("arial.ttf", 24)
    draw.text((50, 250), "Custom Font", font=font, fill='blue')
except:
    # 使用默认字体
    font = ImageFont.load_default()
    draw.text((50, 250), "Default Font", font=font, fill='blue')
# 获取文本尺寸
text = "Measure me"
bbox = draw.textbbox((0, 0), text, font=font)
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]

高级绘制功能

# 绘制圆弧
draw.arc([100, 100, 200, 200], start=0, end=180, fill='red', width=3)
# 绘制扇形
draw.pieslice([250, 100, 350, 200], start=0, end=90, fill='green')
# 绘制多条线段
points = [(0, 150), (100, 100), (200, 150), (300, 100), (400, 150)]
draw.line(points, fill='purple', width=2)

ImageFilter 模块 - 图像滤镜

ImageFilter 模块提供了各种图像滤镜效果。

内置滤镜

from PIL import Image, ImageFilter
img = Image.open('example.jpg')
# 模糊滤镜
blurred = img.filter(ImageFilter.BLUR)
gaussian_blur = img.filter(ImageFilter.GaussianBlur(radius=2))
# 锐化滤镜
sharpened = img.filter(ImageFilter.SHARPEN)
unsharp_mask = img.filter(ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3))
# 边缘检测
edges = img.filter(ImageFilter.FIND_EDGES)
edge_enhance = img.filter(ImageFilter.EDGE_ENHANCE)
# 浮雕效果
embossed = img.filter(ImageFilter.EMBOSS)
# 轮廓检测
contour = img.filter(ImageFilter.CONTOUR)

自定义卷积滤镜

# 创建自定义滤镜内核
from PIL.ImageFilter import Kernel
# 3x3 拉普拉斯算子
laplacian_kernel = Kernel((3, 3), [
    -1, -1, -1,
    -1,  8, -1,
    -1, -1, -1
])
# 应用自定义滤镜
filtered_img = img.filter(laplacian_kernel)
# 5x5 高斯模糊核
gaussian_5x5 = Kernel((5, 5), [
    1,  4,  6,  4, 1,
    4, 16, 24, 16, 4,
    6, 24, 36, 24, 6,
    4, 16, 24, 16, 4,
    1,  4,  6,  4, 1
], scale=256)

ImageEnhance 模块 - 图像增强

ImageEnhance 模块提供了调整图像亮度、对比度、饱和度和锐度的功能。

from PIL import Image, ImageEnhance
img = Image.open('example.jpg')
# 亮度调整
brightness = ImageEnhance.Brightness(img)
bright_img = brightness.enhance(1.5)  # 增加50%亮度
dark_img = brightness.enhance(0.5)    # 减少50%亮度
# 对比度调整
contrast = ImageEnhance.Contrast(img)
high_contrast = contrast.enhance(2.0)  # 增强对比度
low_contrast = contrast.enhance(0.5)   # 降低对比度
# 颜色饱和度调整
color = ImageEnhance.Color(img)
saturated = color.enhance(1.8)    # 增强饱和度
desaturated = color.enhance(0.2)  # 降低饱和度(接近灰度)
# 锐度调整
sharpness = ImageEnhance.Sharpness(img)
sharp_img = sharpness.enhance(2.0)  # 增强锐度
soft_img = sharpness.enhance(0.5)   # 降低锐度

ImageOps dwAtwkpz模块 - 图像操作

ImageOps 模块提供了许多实用的图像操作函数。

from PIL import Image, ImageOps
img = Image.open('example.jpg')
# 自动对比度
autocontrast_img = ImageOps.autocontrast(img)
# 颜色均衡
equalized_img = ImageOps.equalize(img)
# 反转颜色
inverted_img = ImageOps.invert(img)
# 灰度化
grayscale_img = ImageOps.grayscale(img)
# 镜像翻转
mirrored_img = ImageOps.mirror(img)
# 适应尺寸(保持宽高比)
fitted_img = ImageOps.fit(img, (300, 300), method=Image.LANCZOS)
# 添加javascript边框
bordered_img = ImageOps.expand(img, border=20, fill='black')
# 色调分离
posterized_img = ImageOps.posterize(img, bits=4)
# 曝光度调整
solarized_img = ImageOps.solarize(img, threshold=128)

ImageColor 模块 - 颜色处理

ImageColor 模块提供了颜色格式转换和颜色名称解析功能。

from PIL import ImageColor
# 颜色名称转RGB
red_rgb = ImageColor.getrgb('red')  # (255, 0, 0)
blue_rgb = ImageColor.getrgb('#0000FF')  # (0, 0, 255)
# 转换为RGBA
red_rgba = ImageColor.getcolor('red', 'RGBA')  # (255, 0, 0, 255)
# HSL转RGB
hsl_color = ImageColor.getcolor('hsl(120, 100%, 50%)', 'RGB')  # (0, 255, 0)
# 支持的颜色格式
formats = [
    'red',                    # 颜色名称
    '#FF0000',               # 十六进制
    'rgb(255, 0, 0)',        # RGB函数
    'rgba(255, 0, 0, 1.0)',  # RGBA函数
    'hsl(0, 100%, 50%)',     # HSL函数
]

ImageFont 模块 - 字体处理

ImageFont 模块用于加载和使用字体文件。

from PIL import Image, ImageDraw, ImageFont
# 加载TrueType字体
try:
    font_large = ImageFont.truetype("arial.ttf", 36)
    font_small = ImageFont.truetype("arial.ttf", 16)
except:
    # 使用默认字体
    font_large = ImageFont.load_default()
    font_small = ImageFont.load_default()
# 使用字体绘制文本
img = Image.new('RGB', (400, 200), 'white')
draw = ImageDraw.Draw(img)
draw.text((10, 10), "Large Text", font=font_large, fill='black')
draw.text((10, 60), "Small Text", font=font_small, fill='gray')
# 获取字体指标
ascent, descent = font_large.getmetrics()
text_size = font_large.getsize("Sample Text")

实际应用示例

图像批处理

import os
from PIL import Image
def BATch_resize(input_dir, output_dir, size=(800, 600)):
    """批量调整图像尺寸"""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    for filename in os.listdir(input_dir):
        if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp')):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)
            try:
                with Image.open(input_path) as img:
                    img.thumbnail(size, Image.LANCZOS)
                    img.save(output_path, optimize=True, quality=85)
                    print(f"处理完成: {filename}")
            except Exception as e:
                print(f"处理失败 {filename}: {e}")

水印添加

def add_watermark(image_path, watermark_text, output_path):
    """为图像添加文字水印"""
    with Image.open(image_path) as img:
        # 创建透明层
        overlay = Image.new('RGBA', img.size, (255, 255, 255, 0))
        draw = ImageDraw.Draw(overlay)
        # 设置字体和位置
        try:
            font = ImageFont.truetype("arial.ttf", 36)
        except:
            font = ImageFont.load_default()
        # 计算文本位置(右下角)
        text_bbox = draw.textbbox((0, 0), watermark_text, font=font)
        text_width = text_bbox[2] - text_bbox[0]
        text_height = text_bbox[3] - text_bbox[1]
        x = img.width - text_width - 20
        y = img.height - text_height - 20
        # 绘制半透明文字
        draw.text((x, y), watermark_text, font=font, fill=(255, 255, 255, 128))
        # 合并图层
        watermarked = Image.alpha_composite(img.convert('RGBA'), overlay)
        watermarked.convert('RGB').save(output_path, quality=95)

图像格式转换

def convert_format(input_path, output_path, output_format='JPEG'):
    """转换图像格式"""
    with Image.open(input_path) as img:
        # 如果目标格式不支持透明度,转换为RGB
        if output_format in ['JPEG', 'BMP'] and img.mode in ['RGBA', 'LA']:
            background = Image.new('RGB', img.size, (255, 255, 255))
            background.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
            img = background
        img.save(output_path, format=output_format, quality=95)

创建图像拼贴

def create_collage(image_paths, output_path, cols=3, spacing=10):
    """创建图像拼贴"""
    images = []
    for path in image_paths:
        img = Image.open(path)
        img.thumbnail((200, 200), Image.LANCZOS)
        images.append(img)
    # 计算拼贴尺寸
    rows = (len(images) + cols - 1) // cols
    max_width = max(img.width for img in images)
    max_height = max(img.height for img in images)
    total_width = cjsols * max_width + (cols - 1) * spacing
    total_height = rows * max_height + (rows - 1) * spacing
    # 创建拼贴画布
    collage = Image.new('RGB', (total_width, total_height), 'white')
    # 粘贴图像
    for i, img in enumerate(images):
        row = i // cols
        col = i % cols
        x = col * (max_width + spacing)
        y = row * (max_height + spacing)
        collage.paste(img, (x, y))
    collage.save(output_path, quality=95)

性能优化建议

使用 Pillow 进行图像处理时,应该注意内存管理和性能优化。对于大图像处理,建议使用 with 语句确保及时释放资源,选择合适的重采样算法以平衡质量和速度。批处理时可以考虑多线程处理以提高效率,同时注意设置合适的图像质量参数以控制输出文件大小。

对于需要处理大量图像的应用,可以考虑结合 NumPy 进行数值计算,或使用 Pillow-SIMD 等优化版本来获得更好的性能表现。在 Web 应用中使用时,应该注意设置合理的图像尺寸限制和格式检查,以防止恶意文件攻击。

错误处理和调试

在实际应用中,应该对图像操作进行适当的错误处理,检查文件存在性、格式支持性和内存限制等问题。Pillow 提供了详细的异常信息,可以帮助快速定位和解决问题。建议在生产环境中添加日志记录,以便追踪图像处理的执行情况和性能指标。

到此这篇关于Python Pillow 库详解文档的文章就介绍到这了,更多相关Python Pillow 库内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于Python Pillow 库详解文档(最新推荐)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1155165

相关文章

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A

基于Python开发一个图像水印批量添加工具

《基于Python开发一个图像水印批量添加工具》在当今数字化内容爆炸式增长的时代,图像版权保护已成为创作者和企业的核心需求,本方案将详细介绍一个基于PythonPIL库的工业级图像水印解决方案,有需要... 目录一、系统架构设计1.1 整体处理流程1.2 类结构设计(扩展版本)二、核心算法深入解析2.1 自

从入门到进阶讲解Python自动化Playwright实战指南

《从入门到进阶讲解Python自动化Playwright实战指南》Playwright是针对Python语言的纯自动化工具,它可以通过单个API自动执行Chromium,Firefox和WebKit... 目录Playwright 简介核心优势安装步骤观点与案例结合Playwright 核心功能从零开始学习

Python 字典 (Dictionary)使用详解

《Python字典(Dictionary)使用详解》字典是python中最重要,最常用的数据结构之一,它提供了高效的键值对存储和查找能力,:本文主要介绍Python字典(Dictionary)... 目录字典1.基本特性2.创建字典3.访问元素4.修改字典5.删除元素6.字典遍历7.字典的高级特性默认字典

Python自动化批量重命名与整理文件系统

《Python自动化批量重命名与整理文件系统》这篇文章主要为大家详细介绍了如何使用Python实现一个强大的文件批量重命名与整理工具,帮助开发者自动化这一繁琐过程,有需要的小伙伴可以了解下... 目录简介环境准备项目功能概述代码详细解析1. 导入必要的库2. 配置参数设置3. 创建日志系统4. 安全文件名处

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处

MySQL 主从复制部署及验证(示例详解)

《MySQL主从复制部署及验证(示例详解)》本文介绍MySQL主从复制部署步骤及学校管理数据库创建脚本,包含表结构设计、示例数据插入和查询语句,用于验证主从同步功能,感兴趣的朋友一起看看吧... 目录mysql 主从复制部署指南部署步骤1.环境准备2. 主服务器配置3. 创建复制用户4. 获取主服务器状态5

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

Java docx4j高效处理Word文档的实战指南

《Javadocx4j高效处理Word文档的实战指南》对于需要在Java应用程序中生成、修改或处理Word文档的开发者来说,docx4j是一个强大而专业的选择,下面我们就来看看docx4j的具体使用... 目录引言一、环境准备与基础配置1.1 Maven依赖配置1.2 初始化测试类二、增强版文档操作示例2.

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断