当前位置: 代码网 > it编程>前端脚本>Python > Python Pillow 库详解文档(最新推荐)

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

2025年06月21日 Python 我要评论
python pillow 库详解文档简介pillow (pil fork) 是 python 中最流行的图像处理库,它是 python imaging library (pil) 的现代分支和继承者

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.transpose(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 模块 - 图像操作

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)
# 添加边框
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 = cols * 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 库内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com