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

相关文章

Python按照24个实用大方向精选的上千种工具库汇总整理

《Python按照24个实用大方向精选的上千种工具库汇总整理》本文整理了Python生态中近千个库,涵盖数据处理、图像处理、网络开发、Web框架、人工智能、科学计算、GUI工具、测试框架、环境管理等多... 目录1、数据处理文本处理特殊文本处理html/XML 解析文件处理配置文件处理文档相关日志管理日期和

Python标准库datetime模块日期和时间数据类型解读

《Python标准库datetime模块日期和时间数据类型解读》文章介绍Python中datetime模块的date、time、datetime类,用于处理日期、时间及日期时间结合体,通过属性获取时间... 目录Datetime常用类日期date类型使用时间 time 类型使用日期和时间的结合体–日期时间(

使用Python开发一个Ditto剪贴板数据导出工具

《使用Python开发一个Ditto剪贴板数据导出工具》在日常工作中,我们经常需要处理大量的剪贴板数据,下面将介绍如何使用Python的wxPython库开发一个图形化工具,实现从Ditto数据库中读... 目录前言运行结果项目需求分析技术选型核心功能实现1. Ditto数据库结构分析2. 数据库自动定位3

Python yield与yield from的简单使用方式

《Pythonyield与yieldfrom的简单使用方式》生成器通过yield定义,可在处理I/O时暂停执行并返回部分结果,待其他任务完成后继续,yieldfrom用于将一个生成器的值传递给另一... 目录python yield与yield from的使用代码结构总结Python yield与yield

Go语言使用select监听多个channel的示例详解

《Go语言使用select监听多个channel的示例详解》本文将聚焦Go并发中的一个强力工具,select,这篇文章将通过实际案例学习如何优雅地监听多个Channel,实现多任务处理、超时控制和非阻... 目录一、前言:为什么要使用select二、实战目标三、案例代码:监听两个任务结果和超时四、运行示例五

python使用Akshare与Streamlit实现股票估值分析教程(图文代码)

《python使用Akshare与Streamlit实现股票估值分析教程(图文代码)》入职测试中的一道题,要求:从Akshare下载某一个股票近十年的财务报表包括,资产负债表,利润表,现金流量表,保存... 目录一、前言二、核心知识点梳理1、Akshare数据获取2、Pandas数据处理3、Matplotl

Linux线程同步/互斥过程详解

《Linux线程同步/互斥过程详解》文章讲解多线程并发访问导致竞态条件,需通过互斥锁、原子操作和条件变量实现线程安全与同步,分析死锁条件及避免方法,并介绍RAII封装技术提升资源管理效率... 目录01. 资源共享问题1.1 多线程并发访问1.2 临界区与临界资源1.3 锁的引入02. 多线程案例2.1 为

Django开发时如何避免频繁发送短信验证码(python图文代码)

《Django开发时如何避免频繁发送短信验证码(python图文代码)》Django开发时,为防止频繁发送验证码,后端需用Redis限制请求频率,结合管道技术提升效率,通过生产者消费者模式解耦业务逻辑... 目录避免频繁发送 验证码1. www.chinasem.cn避免频繁发送 验证码逻辑分析2. 避免频繁

精选20个好玩又实用的的Python实战项目(有图文代码)

《精选20个好玩又实用的的Python实战项目(有图文代码)》文章介绍了20个实用Python项目,涵盖游戏开发、工具应用、图像处理、机器学习等,使用Tkinter、PIL、OpenCV、Kivy等库... 目录① 猜字游戏② 闹钟③ 骰子模拟器④ 二维码⑤ 语言检测⑥ 加密和解密⑦ URL缩短⑧ 音乐播放

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group