PythonPIL案例怎么编写?

wen python案例 1

本文目录导读:

  1. 基础安装
  2. 图像基础操作案例
  3. 图像处理效果案例
  4. 图像合成案例
  5. 高级应用案例
  6. 实用工具函数
  7. 最佳实践建议

我来介绍几个Python PIL(Pillow)库的实用案例:

基础安装

pip install Pillow

图像基础操作案例

1 图像打开、显示和保存

from PIL import Image
# 打开图像
img = Image.open('example.jpg')
print(f"图像尺寸: {img.size}")
print(f"图像模式: {img.mode}")
print(f"图像格式: {img.format}")
# 显示图像
img.show()
# 保存图像
img.save('output.jpg', quality=95)

2 图像缩放和裁剪

from PIL import Image
# 打开图像
img = Image.open('example.jpg')
# 缩放图像
resized_img = img.resize((300, 200))
resized_img.save('resized.jpg')
# 裁剪图像 (left, upper, right, lower)
cropped_img = img.crop((100, 100, 400, 400))
cropped_img.save('cropped.jpg')
# 按比例缩放
width, height = img.size
new_width = 500
new_height = int(height * new_width / width)
resized_proportional = img.resize((new_width, new_height))
resized_proportional.save('resized_proportional.jpg')

图像处理效果案例

1 颜色变换

from PIL import Image, ImageEnhance
img = Image.open('example.jpg')
# 灰度转换
gray_img = img.convert('L')
gray_img.save('gray.jpg')
# 调整亮度
enhancer = ImageEnhance.Brightness(img)
bright_img = enhancer.enhance(1.5)  # 亮度增加50%
bright_img.save('bright.jpg')
# 调整对比度
enhancer = ImageEnhance.Contrast(img)
contrast_img = enhancer.enhance(2.0)  # 对比度增加100%
contrast_img.save('contrast.jpg')
# 调整饱和度
enhancer = ImageEnhance.Color(img)
saturated_img = enhancer.enhance(0.5)  # 饱和度降低50%
saturated_img.save('saturated.jpg')

2 滤镜效果

from PIL import Image, ImageFilter
img = Image.open('example.jpg')
# 模糊效果
blurred_img = img.filter(ImageFilter.BLUR)
blurred_img.save('blurred.jpg')
# 高斯模糊
gaussian_blur = img.filter(ImageFilter.GaussianBlur(radius=5))
gaussian_blur.save('gaussian_blur.jpg')
# 边缘检测
edge_img = img.filter(ImageFilter.FIND_EDGES)
edge_img.save('edges.jpg')
# 锐化
sharp_img = img.filter(ImageFilter.SHARPEN)
sharp_img.save('sharpened.jpg')
# 浮雕效果
emboss_img = img.filter(ImageFilter.EMBOSS)
emboss_img.save('emboss.jpg')

图像合成案例

1 图像叠加和拼接

from PIL import Image
# 打开两张图像
img1 = Image.open('image1.jpg')
img2 = Image.open('image2.jpg')
# 水平拼接
new_width = img1.width + img2.width
new_height = max(img1.height, img2.height)
horizontal_combined = Image.new('RGB', (new_width, new_height))
horizontal_combined.paste(img1, (0, 0))
horizontal_combined.paste(img2, (img1.width, 0))
horizontal_combined.save('horizontal_combined.jpg')
# 垂直拼接
new_width = max(img1.width, img2.width)
new_height = img1.height + img2.height
vertical_combined = Image.new('RGB', (new_width, new_height))
vertical_combined.paste(img1, (0, 0))
vertical_combined.paste(img2, (0, img1.height))
vertical_combined.save('vertical_combined.jpg')

2 添加水印

from PIL import Image, ImageDraw, ImageFont
def add_watermark(input_image, output_image, text="Watermark", position=(10, 10)):
    # 打开图像并转换为RGBA模式
    img = Image.open(input_image).convert('RGBA')
    # 创建水印层
    watermark = Image.new('RGBA', img.size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(watermark)
    # 设置字体
    try:
        font = ImageFont.truetype('arial.ttf', 36)
    except:
        font = ImageFont.load_default()
    # 绘制水印文本
    draw.text(position, text, font=font, fill=(255, 255, 255, 128))
    # 合并图像
    watermarked = Image.alpha_composite(img, watermark)
    watermarked = watermarked.convert('RGB')
    watermarked.save(output_image)
# 使用示例
add_watermark('example.jpg', 'watermarked.jpg', 'My Watermark')

高级应用案例

1 生成缩略图

from PIL import Image
import os
def create_thumbnail(input_path, output_path, size=(150, 150)):
    with Image.open(input_path) as img:
        # 创建缩略图(保持比例)
        img.thumbnail(size)
        img.save(output_path)
        print(f"缩略图已保存: {output_path}")
# 批量生成缩略图
def batch_create_thumbnails(input_dir, output_dir, size=(150, 150)):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    for filename in os.listdir(input_dir):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)
            create_thumbnail(input_path, output_path, size)
# 使用示例
# batch_create_thumbnails('images/', 'thumbnails/')

2 图像格式转换批量处理

from PIL import Image
import os
import glob
def convert_images(input_pattern, output_format='PNG'):
    """
    批量转换图像格式
    参数:
    input_pattern: 输入文件匹配模式,如 '*.jpg'
    output_format: 输出格式,如 'PNG', 'JPEG'
    """
    for filepath in glob.glob(input_pattern):
        try:
            # 获取文件名和路径
            dir_path = os.path.dirname(filepath)
            filename = os.path.basename(filepath)
            name_without_ext = os.path.splitext(filename)[0]
            # 打开图像
            with Image.open(filepath) as img:
                # 转换并保存
                output_path = os.path.join(dir_path, f"{name_without_ext}.{output_format.lower()}")
                if output_format.upper() == 'JPEG':
                    # JPEG需要RGB模式
                    if img.mode != 'RGB':
                        img = img.convert('RGB')
                    img.save(output_path, 'JPEG', quality=90)
                else:
                    img.save(output_path, output_format)
                print(f"转换完成: {filename} -> {output_path}")
        except Exception as e:
            print(f"转换失败 {filepath}: {str(e)}")
# 使用示例
# convert_images('*.jpg', 'PNG')

3 图像直方图均衡化

from PIL import Image
import numpy as np
def histogram_equalization(image_path, output_path):
    # 打开图像并转为灰度
    img = Image.open(image_path).convert('L')
    # 转换为numpy数组
    img_array = np.array(img)
    # 计算直方图
    hist, bins = np.histogram(img_array.flatten(), 256, [0, 256])
    # 计算累积分布函数
    cdf = hist.cumsum()
    cdf_normalized = cdf * 255 / cdf[-1]
    # 应用均衡化
    img_equalized = np.interp(img_array.flatten(), bins[:-1], cdf_normalized)
    img_equalized = img_equalized.reshape(img_array.shape).astype('uint8')
    # 保存结果
    result_img = Image.fromarray(img_equalized)
    result_img.save(output_path)
    return result_img
# 使用示例
# equalized = histogram_equalization('dark_image.jpg', 'equalized.jpg')

实用工具函数

1 图像信息查看

from PIL import Image
from PIL.ExifTags import TAGS
def get_image_info(image_path):
    img = Image.open(image_path)
    info = {
        'format': img.format,
        'mode': img.mode,
        'size': img.size,
        'width': img.width,
        'height': img.height,
        'info': img.info
    }
    # 获取EXIF信息
    exif_data = {}
    if hasattr(img, '_getexif') and img._getexif():
        for tag_id, value in img._getexif().items():
            tag = TAGS.get(tag_id, tag_id)
            exif_data[tag] = value
    return info, exif_data
# 使用示例
# info, exif = get_image_info('example.jpg')
# print("图像信息:", info)
# print("EXIF数据:", exif)

2 创建简单图像

from PIL import Image, ImageDraw, ImageFont
def create_simple_image(width=400, height=300, background_color='lightblue'):
    # 创建新图像
    img = Image.new('RGB', (width, height), background_color)
    # 创建绘图对象
    draw = ImageDraw.Draw(img)
    # 绘制矩形
    draw.rectangle([50, 50, 350, 250], outline='blue', width=3)
    # 绘制椭圆
    draw.ellipse([100, 100, 300, 200], fill='yellow', outline='orange')
    # 绘制线条
    draw.line([0, 0, width, height], fill='red', width=5)
    # 添加文本
    try:
        font = ImageFont.truetype('arial.ttf', 24)
    except:
        font = ImageFont.load_default()
    draw.text((100, 130), "Hello PIL!", fill='black', font=font)
    img.save('simple_image.png')
    return img
# 使用示例
# img = create_simple_image()

最佳实践建议

  1. 使用上下文管理器with Image.open('file.jpg') as img:
  2. 处理大图像时注意内存:使用thumbnail()而不是resize()
  3. 格式转换注意事项
    • JPEG不支持透明度
    • GIF转换为PNG可以保留更多颜色
  4. 错误处理:始终使用try-except捕获图像处理异常

这些案例覆盖了PIL/Pillow的主要功能,你可以根据实际需求组合使用,记住要安装Pillow库:pip install Pillow

标签: PIL库

抱歉,评论功能暂时关闭!