Python 三方模块 Pillow
Pillow是Python中最流行的图像处理库,是PIL(Python Imaging Library)的现代化分支。本章节主要讲解 基本图像操作,打开和显示图像,创建新图像,保存图像,图像变换操作,尺寸调整,旋转和翻转,裁剪图像,图像滤镜和效果,应用滤镜,颜色调整,文字和绘图操作,在图像上添加文字,绘制图形,颜色模式转换,不同颜色模式转换,图像信息获取,获取详细信息,批量处理,批量调整图像尺寸,常见应用场景,制作水印等等。
pip install Pillow
基本图像操作
打开和显示图像
from PIL import Image
# 打开图像
img = Image.open('example.jpg')
# 显示图像基本信息
print(f"格式: {img.format}")
print(f"模式: {img.mode}")
print(f"尺寸: {img.size}")
# 显示图像(会打开默认图像查看器)
img.show()
创建新图像
from PIL import Image
# 创建RGB图像
new_img = Image.new('RGB', (300, 200), color='red')
new_img.save('red_image.png')
# 创建带透明度的图像
transparent_img = Image.new('RGBA', (200, 200), (255, 0, 0, 128))
transparent_img.save('transparent_red.png')
保存图像
from PIL import Image
img = Image.open('input.jpg')
# 保存为不同格式
img.save('output.png')
img.save('output.gif')
# 保存时设置质量(仅对JPEG有效)
img.save('compressed.jpg', quality=50)
图像变换操作
尺寸调整
from PIL import Image
img = Image.open('example.jpg')
# 按比例缩放
resized_img = img.resize((400, 300))
resized_img.save('resized.jpg')
# 按比例缩放(保持宽高比)
img.thumbnail((200, 200))
img.save('thumbnail.jpg')
旋转和翻转
from PIL import Image
img = Image.open('example.jpg')
# 旋转图像
rotated_img = img.rotate(45)
rotated_img.save('rotated.jpg')
# 水平翻转
flipped_h = img.transpose(Image.FLIP_LEFT_RIGHT)
flipped_h.save('flipped_horizontal.jpg')
# 垂直翻转
flipped_v = img.transpose(Image.FLIP_TOP_BOTTOM)
flipped_v.save('flipped_vertical.jpg')
裁剪图像
from PIL import Image
img = Image.open('example.jpg')
# 裁剪图像 (左, 上, 右, 下)
cropped_img = img.crop((100, 100, 400, 300))
cropped_img.save('cropped.jpg')
# 居中裁剪
width, height = img.size
left = (width - 200) // 2
top = (height - 200) // 2
right = left + 200
bottom = top + 200
center_crop = img.crop((left, top, right, bottom))
center_crop.save('center_crop.jpg')
图像滤镜和效果
应用滤镜
from PIL import Image, ImageFilter
img = Image.open('example.jpg')
# 模糊效果
blurred = img.filter(ImageFilter.BLUR)
blurred.save('blurred.jpg')
# 锐化效果
sharpened = img.filter(ImageFilter.SHARPEN)
sharpened.save('sharpened.jpg')
# 边缘检测
edges = img.filter(ImageFilter.FIND_EDGES)
edges.save('edges.jpg')
# 浮雕效果
embossed = img.filter(ImageFilter.EMBOSS)
embossed.save('embossed.jpg')
颜色调整
from PIL import Image, ImageEnhance
img = Image.open('example.jpg')
# 调整亮度
brightness = ImageEnhance.Brightness(img)
bright_img = brightness.enhance(1.5) # 1.5倍亮度
bright_img.save('bright.jpg')
# 调整对比度
contrast = ImageEnhance.Contrast(img)
contrast_img = contrast.enhance(1.3)
contrast_img.save('contrast.jpg')
# 调整饱和度
color = ImageEnhance.Color(img)
saturated_img = color.enhance(1.5)
saturated_img.save('saturated.jpg')
# 调整锐度
sharpness = ImageEnhance.Sharpness(img)
sharp_img = sharpness.enhance(2.0)
sharp_img.save('enhanced_sharp.jpg')
文字和绘图操作
在图像上添加文字
from PIL import Image, ImageDraw, ImageFont
# 创建图像
img = Image.new('RGB', (400, 200), color='white')
draw = ImageDraw.Draw(img)
# 添加文字
draw.text((10, 50), "Hello Pillow!", fill='black')
# 使用自定义字体(如果有字体文件)
try:
font = ImageFont.truetype("arial.ttf", 20)
draw.text((10, 100), "自定义字体", font=font, fill='blue')
except:
draw.text((10, 100), "默认字体", fill='blue')
img.save('text_image.png')
绘制图形
from PIL import Image, ImageDraw
img = Image.new('RGB', (300, 300), color='white')
draw = ImageDraw.Draw(img)
# 绘制矩形
draw.rectangle([50, 50, 150, 100], fill='red', outline='black')
# 绘制圆形
draw.ellipse([200, 50, 250, 100], fill='blue', outline='black')
# 绘制线条
draw.line([0, 0, 300, 300], fill='green', width=3)
# 绘制多边形
points = [(100, 200), (150, 150), (200, 200), (175, 250), (125, 250)]
draw.polygon(points, fill='yellow', outline='purple')
img.save('shapes.png')
颜色模式转换
不同颜色模式转换
from PIL import Image
img = Image.open('example.jpg')
# 转换为灰度图
gray_img = img.convert('L')
gray_img.save('gray.jpg')
# 转换为黑白图
bw_img = img.convert('1')
bw_img.save('blackwhite.jpg')
# RGB转RGBA(添加透明通道)
rgba_img = img.convert('RGBA')
rgba_img.save('rgba.png')
# CMYK模式(印刷用)
cmyk_img = img.convert('CMYK')
cmyk_img.save('cmyk.jpg')
图像信息获取
获取详细信息
from PIL import Image
from PIL.ExifTags import TAGS
img = Image.open('example.jpg')
# 基本信息
print(f"文件名: {img.filename}")
print(f"格式: {img.format}")
print(f"模式: {img.mode}")
print(f"尺寸: {img.size}")
print(f"宽度: {img.width}")
print(f"高度: {img.height}")
# 获取EXIF信息(如果存在)
try:
exifdata = img.getexif()
for tag_id in exifdata:
tag = TAGS.get(tag_id, tag_id)
data = exifdata.get(tag_id)
print(f"{tag}: {data}")
except:
print("无EXIF信息")
批量处理
批量调整图像尺寸
from PIL import Image
import os
def batch_resize(input_folder, output_folder, size=(800, 600)):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
try:
img_path = os.path.join(input_folder, filename)
img = Image.open(img_path)
# 调整尺寸
img.thumbnail(size, Image.Resampling.LANCZOS)
# 保存
output_path = os.path.join(output_folder, filename)
img.save(output_path)
print(f"处理完成: {filename}")
except Exception as e:
print(f"处理失败 {filename}: {e}")
# 使用示例
# batch_resize('input_images', 'resized_images', (400, 300))
常见应用场景
制作水印
from PIL import Image, ImageDraw, ImageFont
def add_watermark(image_path, watermark_text, output_path):
img = Image.open(image_path).convert('RGBA')
# 创建透明图层
watermark = Image.new('RGBA', img.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(watermark)
# 计算文字位置(右下角)
width, height = img.size
text_width = len(watermark_text) * 10
x = width - text_width - 20
y = height - 30
# 添加半透明文字
draw.text((x, y), watermark_text, fill=(255, 255, 255, 128))
# 合并图像
watermarked = Image.alpha_composite(img, watermark)
watermarked.convert('RGB').save(output_path)
# 使用示例
# add_watermark('photo.jpg', '© 2024 My Photo', 'watermarked.jpg')