PythonPillow库详解文档(最新推荐)

Written by

in

文章目录
  • 目录
    • Python Pillow 库详解文档
      • 简介
      • 安装
      • 核心模块架构
      • Image 模块 – 核心图像处理
        • 基本导入和使用
        • 图像创建与打开
        • 图像基本属性和信息
        • 图像变换操作
        • 图像模式转换
      • ImageDraw 模块 – 图形绘制
        • 基础绘制操作
        • 文本绘制
        • 高级绘制功能
      • ImageFilter 模块 – 图像滤镜
        • 内置滤镜
        • 自定义卷积滤镜
      • ImageEnhance 模块 – 图像增强
        • ImageOps 模块 – 图像操作
          • ImageColor 模块 – 颜色处理
            • ImageFont 模块 – 字体处理
              • 实际应用示例
              • 图像批处理
              • 水印添加
              • 图像格式转换
              • 创建图像拼贴
            • 性能优化建议
              • 错误处理和调试

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

              pip install Pillow

              Pillow 库的核心围绕 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 模块提供了在图像上绘制各种图形和文本的功能。

              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 模块提供了各种图像滤镜效果。

              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 模块提供了调整图像亮度、对比度、饱和度和锐度的功能。

              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 模块提供了许多实用的图像操作函数。

              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 模块提供了颜色格式转换和颜色名称解析功能。

              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 模块用于加载和使用字体文件。

              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 库内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

              您可能感兴趣的文章:

              • Python的图像处理库Pillow安装与使用教程
              • Python图像处理Pillow库的安装使用
              • Python详细讲解图像处理的而两种库OpenCV和Pillow
              • Python的Pillow库进行图像文件处理(图文详解)
              • Python 图像处理 Pillow 库详情
              • python图片处理库Pillow实现简单PS功能
              • Python Pillow(PIL)库的用法详解

              站内搜索