ai
  • index
  • cursor
  • vector
  • crawl
  • crawl-front
  • DrissionPage
  • logging
  • mysql
  • pprint
  • sqlalchemy
  • contextmanager
  • dotenv
  • Flask
  • python
  • job
  • pdfplumber
  • python-docx
  • redbook
  • douyin
  • ffmpeg
  • json
  • numpy
  • opencv-python
  • pypinyin
  • re
  • requests
  • subprocess
  • time
  • uuid
  • watermark
  • milvus
  • pymilvus
  • search
  • Blueprint
  • flash
  • Jinja2
  • secure_filename
  • url_for
  • Werkzeug
  • chroma
  • HNSW
  • pillow
  • pandas
  • beautifulsoup4
  • langchain-community
  • langchain-core
  • langchain
  • langchain_unstructured
  • libreoffice
  • lxml
  • openpyxl
  • pymupdf
  • python-pptx
  • RAGFlow
  • tabulate
  • sentence_transformers
  • jsonl
  • collections
  • jieba
  • rag_optimize
  • rag
  • rank_bm25
  • Hugging_Face
  • modelscope
  • all-MiniLM-L6-v2
  • ollama
  • rag_measure
  • ragas
  • ASGI
  • FastAPI
  • FastChat
  • Jupyter
  • PyTorch
  • serper
  • uvicorn
  • markdownify
  • NormalizedLevenshtein
  • raq-action
  • CrossEncoder
  • Bi-Encoder
  • neo4j
  • neo4j4python
  • matplotlib
  • Plotly
  • Streamlit
  • py2neo
  • abc
  • read_csv
  • neo4jinstall
  • APOC
  • neo4jproject
  • uv
  • GDS
  • heapq
  • 一、Pillow基础
    • 1. 安装Pillow
    • 2. 核心功能概述
  • 二、基本图像操作
    • 1. 打开和显示图像
    • 2. 保存图像
    • 3. 图像转换
  • 三、图像处理操作
    • 1. 调整大小和裁剪
    • 2. 旋转和翻转
    • 3. 颜色分离与合并
  • 四、图像增强
    • 1. 使用ImageEnhance模块
    • 2. 滤波操作
  • 五、绘制图像
    • 1. 基本绘图
    • 2. 使用字体
  • 六、高级功能
    • 1. 图像序列处理(GIF)
    • 2. 图像混合
    • 3. 像素级操作
  • 七、Pillow与其他库结合
    • 1. 与NumPy结合
    • 2. 与Matplotlib结合
  • 八、性能优化技巧
  • 九、常见图像处理任务示例
    • 1. 创建验证码图片
    • 2. 批量图像处理
  • 十、Pillow支持的图像格式

Pillow是Python中最流行的图像处理库,是Python Imaging Library(PIL)的一个友好分支。它提供了广泛的图像处理功能,支持多种图像格式,是计算机视觉、网页开发和图像处理应用的基础工具。

一、Pillow基础 #

本节介绍Pillow库的安装方法及其主要功能,帮助你快速了解Pillow的基本用途。

1. 安装Pillow #

# 安装Pillow库
pip install pillow

2. 核心功能概述 #

  • 图像打开、保存和格式转换
  • 基本图像操作(裁剪、旋转、调整大小)
  • 颜色空间转换
  • 图像增强(锐化、模糊等)
  • 文本和图形绘制
  • 图像滤波和卷积操作

二、基本图像操作 #

本节讲解如何用Pillow进行图像的打开、显示、保存、格式转换等基础操作。

1. 打开和显示图像 #

# 导入Image模块
from PIL import Image

# 打开图像文件example.jpg
img = Image.open("example.jpg")

# 显示图像
img.show()

# 打印图像的格式、尺寸和模式
print(f"格式: {img.format}, 大小: {img.size}, 模式: {img.mode}")

2. 保存图像 #

# 导入Image模块
from PIL import Image

# 打开图像文件
img = Image.open("example.jpg")

# 保存为PNG格式
img.save("example.png")  # 转换格式

# 保存为JPEG格式并设置质量
img.save("quality.jpg", quality=95)  # 设置JPEG质量

3. 图像转换 #

# 导入Image和numpy模块
from PIL import Image
import numpy as np

# 打开图像文件
img = Image.open("example.jpg")

# 转换为灰度图像
gray_img = img.convert("L")

# 转换为RGB模式
rgb_img = img.convert("RGB")

# 转换为NumPy数组
img_array = np.array(img)

三、图像处理操作 #

本节介绍如何用Pillow进行图像的缩放、裁剪、旋转、翻转、通道分离与合并等常见处理。

1. 调整大小和裁剪 #

# 导入Image模块
from PIL import Image

# 打开图像文件
img = Image.open("example.jpg")

# 直接调整为指定大小
resized_img = img.resize((200, 150))

# 复制一份图像用于生成缩略图
thumbnail_img = img.copy()
# 生成最大边长为100的缩略图,保持比例
thumbnail_img.thumbnail((100, 100))

# 定义裁剪区域(左,上,右,下)
box = (50, 50, 150, 150)
# 裁剪图像
cropped_img = img.crop(box)

2. 旋转和翻转 #

# 导入Image模块
from PIL import Image

# 打开图像文件
img = Image.open("example.jpg")

# 旋转90度,expand=True防止裁剪
rotated_90 = img.rotate(90, expand=True)

# 左右翻转
flipped_lr = img.transpose(Image.FLIP_LEFT_RIGHT)

# 上下翻转
flipped_tb = img.transpose(Image.FLIP_TOP_BOTTOM)

3. 颜色分离与合并 #

# 导入Image模块
from PIL import Image

# 打开图像文件
img = Image.open("example.jpg")

# 分离RGB通道
r, g, b = img.split()

# 合并RGB通道
merged_img = Image.merge("RGB", (r, g, b))

四、图像增强 #

本节讲解如何用Pillow增强图像的对比度、亮度、锐度、颜色等,以及常用滤波操作。

1. 使用ImageEnhance模块 #

# 导入Image和ImageEnhance模块
from PIL import Image, ImageEnhance

# 打开图像文件
img = Image.open("example.jpg")

# 创建对比度增强器
enhancer = ImageEnhance.Contrast(img)
# 增强对比度(1.5倍)
enhanced_img = enhancer.enhance(1.5)

# 创建亮度增强器
brightness = ImageEnhance.Brightness(img)
# 创建锐度增强器
sharpness = ImageEnhance.Sharpness(img)
# 创建颜色增强器
color = ImageEnhance.Color(img)

2. 滤波操作 #

# 导入Image和ImageFilter模块
from PIL import Image, ImageFilter

# 打开图像文件
img = Image.open("example.jpg")

# 模糊滤波
blurred = img.filter(ImageFilter.BLUR)

# 边缘检测
edges = img.filter(ImageFilter.FIND_EDGES)

# 锐化滤波
sharp = img.filter(ImageFilter.SHARPEN)

# 高斯模糊,半径为2
gaussian_blur = img.filter(ImageFilter.GaussianBlur(radius=2))

五、绘制图像 #

本节介绍如何在图像上绘制矩形、椭圆、线条和文本,并自定义字体。

1. 基本绘图 #

# 导入Image和ImageDraw模块
from PIL import Image, ImageDraw, ImageFont

# 创建空白图像
img = Image.new("RGB", (200, 200), (255, 255, 255))
# 创建绘图对象
draw = ImageDraw.Draw(img)

# 绘制红色矩形
x0, y0, x1, y1 = 20, 20, 180, 80
# 绘制矩形
draw.rectangle([(x0, y0), (x1, y1)], outline="red", width=2)

# 绘制蓝色椭圆
draw.ellipse([(50, 100), (150, 180)], fill="blue")

# 绘制绿色折线
draw.line([(20, 190), (100, 120), (180, 190)], fill="green", width=3)

# 加载字体
try:
    font = ImageFont.truetype("arial.ttf", size=20)
except:
    font = ImageFont.load_default()
# 在指定位置绘制文本
x, y = 60, 40
# 绘制文本
draw.text((x, y), "Hello", fill="black", font=font)

# 显示绘制结果
img.show()

2. 使用字体 #

# 导入ImageFont模块
from PIL import ImageFont

# 尝试加载指定字体
try:
    font = ImageFont.truetype("arial.ttf", size=20)
except:
    # 加载默认字体
    font = ImageFont.load_default()

六、高级功能 #

本节介绍Pillow在动态图像(如GIF)、图像混合、像素级操作等高级用法。

1. 图像序列处理(GIF) #

# 导入Image模块
from PIL import Image

# 读取GIF动画的每一帧
with Image.open("animation.gif") as img:
    for i in range(img.n_frames):
        # 跳转到第i帧
        img.seek(i)
        # 这里可以对每一帧进行处理

# 创建GIF动画
# 假设frame1, frame2, frame3是Image对象
frames = [Image.new("RGB", (100, 100), (i*80, 0, 0)) for i in range(3)]
# 保存为GIF
frames[0].save("output.gif", save_all=True, append_images=frames[1:], duration=100, loop=0)

2. 图像混合 #

# 导入Image模块
from PIL import Image

# 打开两张图像,确保大小和模式一致
img1 = Image.open("example1.jpg").resize((200, 200))
img2 = Image.open("example2.jpg").resize((200, 200))

# 透明度混合,alpha为混合比例
blended = Image.blend(img1, img2, alpha=0.3)

# 创建掩码图像(灰度)
mask = Image.new("L", (200, 200), 128)
# 复合操作,mask决定使用哪个图像的像素
composite = Image.composite(img1, img2, mask)

3. 像素级操作 #

# 导入Image模块
from PIL import Image

# 打开图像文件
img = Image.open("example.jpg")

# 获取(x, y)位置的像素值
pixel = img.getpixel((10, 10))

# 修改(x, y)位置的像素值
img.putpixel((10, 10), (255, 0, 0))

# 对所有像素进行亮度增强(每个像素乘以1.2)
img = img.point(lambda x: x * 1.2)

七、Pillow与其他库结合 #

本节讲解Pillow与NumPy、Matplotlib等库的结合使用方法。

1. 与NumPy结合 #

# 导入Image和numpy模块
from PIL import Image
import numpy as np

# 打开图像文件
img = Image.open("example.jpg")

# 图像转NumPy数组
array = np.array(img)

# NumPy数组转图像
new_img = Image.fromarray(array)

2. 与Matplotlib结合 #

# 导入Image、numpy和matplotlib模块
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

# 打开图像文件
img = Image.open("example.jpg")

# 直接显示图像
plt.imshow(np.array(img))
plt.show()

# 多图显示
img1 = Image.open("example1.jpg")
img2 = Image.open("example2.jpg")
fig, axes = plt.subplots(1, 2)
axes[0].imshow(np.array(img1))
axes[1].imshow(np.array(img2))
plt.show()

八、性能优化技巧 #

本节总结Pillow在批量处理、内存管理、模式选择等方面的性能优化建议。

  1. 批量操作:将多个操作合并减少中间图像创建
  2. 适当尺寸:先缩小再处理大图像
  3. 使用缩略图:预览时使用thumbnail()
  4. 内存管理:及时关闭文件句柄
  5. 选择正确模式:处理时使用适当颜色模式(如不需要颜色用"L")

九、常见图像处理任务示例 #

本节给出验证码生成、批量缩放等常见图像处理任务的完整代码示例。

1. 创建验证码图片 #

# 导入所需模块
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random

def generate_captcha(text, width=200, height=80):
    # 创建空白图像
    img = Image.new("RGB", (width, height), (255, 255, 255))
    # 创建绘图对象
    draw = ImageDraw.Draw(img)
    # 加载字体
    try:
        font = ImageFont.truetype("arial.ttf", 40)
    except:
        font = ImageFont.load_default()
    # 逐个绘制字符
    for i, char in enumerate(text):
        # 随机颜色
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        # 绘制字符
        draw.text((20 + i*40, 20), char, fill=color, font=font)
    # 添加干扰线
    for _ in range(5):
        draw.line([(random.randint(0, width), random.randint(0, height)),
                  (random.randint(0, width), random.randint(0, height))],
                 fill=(0, 0, 0), width=2)
    # 添加滤镜效果
    img = img.filter(ImageFilter.SMOOTH)
    return img

# 生成并显示验证码
if __name__ == "__main__":
    captcha = generate_captcha("ABCD")
    captcha.show()

2. 批量图像处理 #

# 导入os和Image模块
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):
        try:
            # 打开图像文件
            with Image.open(os.path.join(input_dir, filename)) as img:
                # 生成缩略图
                img.thumbnail(size)
                # 保存到输出目录
                img.save(os.path.join(output_dir, filename))
        except Exception as e:
            # 打印出错信息
            print(f"处理 {filename} 时出错: {e}")

# 示例:批量缩放input_dir目录下的图片到output_dir
if __name__ == "__main__":
    batch_resize("input_dir", "output_dir")

十、Pillow支持的图像格式 #

本节列出Pillow支持的主要图像格式及其说明,便于查阅。

格式 读取 写入 说明
JPEG ✓ ✓ 常用有损压缩
PNG ✓ ✓ 无损压缩,支持透明
GIF ✓ ✓ 支持动画
BMP ✓ ✓ 无压缩位图
TIFF ✓ ✓ 高质量格式
WebP ✓ ✓ 谷歌现代格式
PPM/PGM ✓ ✓ 便携式像素图

访问验证

请输入访问令牌

Token不正确,请重新输入