Python图像处理神器!Pillow库从入门到精通,这教程太全了
wptr33 2025-07-23 18:43 13 浏览
Pillow是Python中一个强大的图像处理库,是PIL(Python Imaging Library)的分支和升级版本。本教程将介绍Pillow的基本用法和常见操作。
## 安装Pillow
```python
pip install pillow
```
## 基本图像操作
### 1. 打开和显示图像
```python
from PIL import Image
# 打开图像
img = Image.open('example.jpg')
# 显示图像
img.show()
# 获取图像信息
print(f"格式: {img.format}")
print(f"大小: {img.size}") # (宽度, 高度)
print(f"模式: {img.mode}") # RGB, L(灰度), CMYK等
```
### 2. 保存图像
```python
# 保存为不同格式
img.save('example.png') # 转换为PNG格式
img.save('example_quality.jpg', quality=95) # 指定JPEG质量
```
### 3. 图像转换
```python
# 转换为灰度图像
gray_img = img.convert('L')
gray_img.show()
# 转换图像模式
if img.mode != 'RGB':
rgb_img = img.convert('RGB')
```
### 4. 调整图像大小
```python
# 调整尺寸
resized_img = img.resize((300, 200))
resized_img.show()
# 保持宽高比的缩放
width, height = img.size
new_height = 300
new_width = int(width * new_height / height)
aspect_img = img.resize((new_width, new_height))
aspect_img.show()
```
### 5. 旋转和翻转图像
```python
# 旋转90度
rotated_img = img.rotate(90)
rotated_img.show()
# 镜像翻转
flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT)
flipped_img.show()
```
## 图像处理
### 1. 裁剪图像
```python
# 定义裁剪区域 (left, upper, right, lower)
box = (100, 100, 400, 400)
cropped_img = img.crop(box)
cropped_img.show()
```
### 2. 粘贴图像
```python
# 打开另一张图像
logo = Image.open('logo.png')
# 粘贴到指定位置
img.paste(logo, (50, 50))
img.show()
```
### 3. 创建缩略图
```python
# 创建缩略图 (会修改原图像)
img.thumbnail((100, 100))
img.show()
```
### 4. 图像滤镜
```python
from PIL import ImageFilter
# 应用模糊滤镜
blurred_img = img.filter(ImageFilter.BLUR)
blurred_img.show()
# 边缘增强
edge_img = img.filter(ImageFilter.EDGE_ENHANCE)
edge_img.show()
# 更多滤镜
# ImageFilter.CONTOUR - 轮廓
# ImageFilter.DETAIL - 细节增强
# ImageFilter.EMBOSS - 浮雕
# ImageFilter.SHARPEN - 锐化
# ImageFilter.SMOOTH - 平滑
```
## 高级操作
### 1. 绘制图形和文字
```python
from PIL import ImageDraw, ImageFont
# 创建一个可绘制对象
draw = ImageDraw.Draw(img)
# 绘制矩形
draw.rectangle([(100, 100), (200, 200)], outline='red', width=2)
# 绘制文字
try:
font = ImageFont.truetype('arial.ttf', 40)
except:
font = ImageFont.load_default()
draw.text((50, 50), "Hello Pillow", fill='blue', font=font)
img.show()
```
### 2. 像素级操作
```python
# 获取像素值
pixel = img.getpixel((100, 100))
print(f"像素值: {pixel}")
# 设置像素值
img.putpixel((100, 100), (255, 0, 0)) # 设置为红色
# 处理所有像素
pixels = img.load()
for i in range(img.size[0]):
for j in range(img.size[1]):
r, g, b = pixels[i, j]
# 示例:转换为灰度
gray = int(0.299 * r + 0.587 * g + 0.114 * b)
pixels[i, j] = (gray, gray, gray)
img.show()
```
### 3. 图像合成
```python
from PIL import ImageChops
# 打开两张图像
img1 = Image.open('image1.jpg')
img2 = Image.open('image2.jpg')
# 确保大小相同
img2 = img2.resize(img1.size)
# 图像混合
blended_img = Image.blend(img1, img2, alpha=0.5) # alpha是混合比例
blended_img.show()
# 其他合成操作
# ImageChops.add() - 相加
# ImageChops.subtract() - 相减
# ImageChops.multiply() - 相乘
# ImageChops.screen() - 屏幕混合
# ImageChops.darker() - 取较暗像素
# ImageChops.lighter() - 取较亮像素
```
### 4. 批量处理图像
```python
import os
from PIL import Image
input_folder = 'input_images'
output_folder = 'output_images'
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')):
img_path = os.path.join(input_folder, filename)
img = Image.open(img_path)
# 处理图像 - 例如创建缩略图
img.thumbnail((200, 200))
# 保存处理后的图像
output_path = os.path.join(output_folder, f"thumb_{filename}")
img.save(output_path)
```
## 实际应用示例
### 1. 为图片添加水印
```python
def add_watermark(image_path, watermark_text, output_path):
# 打开原始图像
base_image = Image.open(image_path).convert("RGBA")
# 创建一个透明图层用于水印
txt = Image.new("RGBA", base_image.size, (255, 255, 255, 0))
# 获取绘图对象
d = ImageDraw.Draw(txt)
# 尝试加载字体
try:
font = ImageFont.truetype("arial.ttf", 40)
except:
font = ImageFont.load_default()
# 计算文本位置(右下角)
text_width, text_height = d.textsize(watermark_text, font)
x = base_image.width - text_width - 10
y = base_image.height - text_height - 10
# 绘制半透明文本
d.text((x, y), watermark_text, font=font, fill=(255, 255, 255, 128))
# 合并图像
watermarked = Image.alpha_composite(base_image, txt)
# 保存为RGB格式(JPEG不支持透明度)
watermarked.convert("RGB").save(output_path)
# 使用示例
add_watermark("photo.jpg", "My Watermark", "watermarked_photo.jpg")
```
### 2. 创建图片拼贴
```python
def create_collage(image_paths, output_path, collage_size=(1000, 1000), images_per_row=3):
# 计算每个小图的大小
img_width = collage_size[0] // images_per_row
img_height = img_width # 保持正方形
# 创建新图像
collage = Image.new('RGB', collage_size)
x, y = 0, 0
for i, img_path in enumerate(image_paths):
try:
img = Image.open(img_path)
# 调整大小并保持比例
img.thumbnail((img_width, img_height))
# 计算居中位置
paste_x = x + (img_width - img.width) // 2
paste_y = y + (img_height - img.height) // 2
# 粘贴图像
collage.paste(img, (paste_x, paste_y))
# 更新位置
x += img_width
if (i + 1) % images_per_row == 0:
x = 0
y += img_height
except Exception as e:
print(f"无法处理图像 {img_path}: {e}")
collage.save(output_path)
# 使用示例
image_files = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg']
create_collage(image_files, 'collage.jpg')
```
### 3. 生成验证码图片
```python
import random
import string
from PIL import Image, ImageDraw, ImageFont, ImageFilter
def generate_captcha(width=200, height=80, char_length=6):
# 创建图像
image = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(image)
# 生成随机字符
chars = ''.join(random.choices(string.ascii_uppercase + string.digits, k=char_length))
# 使用随机字体大小和位置
font_size = random.randint(30, 40)
try:
font = ImageFont.truetype('arial.ttf', font_size)
except:
font = ImageFont.load_default()
# 绘制每个字符
x = 10
for char in chars:
# 随机颜色
color = (random.randint(0, 150), random.randint(0, 150), random.randint(0, 150))
# 随机y位置
y = random.randint(5, height - font_size - 5)
# 绘制字符
draw.text((x, y), char, fill=color, font=font)
# 随机旋转
# 这里需要创建一个新的临时图像来旋转字符
char_img = Image.new('RGBA', (font_size, font_size), (255, 255, 255, 0))
char_draw = ImageDraw.Draw(char_img)
char_draw.text((0, 0), char, fill=color, font=font)
rotated_char = char_img.rotate(random.randint(-30, 30), expand=1)
# 计算新位置
paste_x = x + (font_size - rotated_char.width) // 2
paste_y = y + (font_size - rotated_char.height) // 2
# 粘贴旋转后的字符
image.paste(rotated_char, (paste_x, paste_y), rotated_char)
x += font_size + random.randint(-5, 5)
# 添加干扰线
for _ in range(5):
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
draw.line([(x1, y1), (x2, y2)], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), width=1)
# 添加噪点
for _ in range(width * height // 20):
draw.point((random.randint(0, width), random.randint(0, height)), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
# 应用模糊滤镜
image = image.filter(ImageFilter.BLUR)
return image, chars
# 使用示例
captcha, text = generate_captcha()
captcha.save('captcha.png')
print(f"验证码文本: {text}")
captcha.show()
```
## 总结
Pillow库提供了丰富的图像处理功能,从基本的图像打开、保存和转换,到高级的滤镜应用、像素级操作和图像合成。通过本教程中的示例,你可以快速掌握Pillow的核心功能,并将其应用到实际项目中,如图片处理工具、网站图像处理、验证码生成等场景。
相关推荐
- MySQL进阶五之自动读写分离mysql-proxy
-
自动读写分离目前,大量现网用户的业务场景中存在读多写少、业务负载无法预测等情况,在有大量读请求的应用场景下,单个实例可能无法承受读取压力,甚至会对业务产生影响。为了实现读取能力的弹性扩展,分担数据库压...
- 3分钟短文 | Laravel SQL筛选两个日期之间的记录,怎么写?
-
引言今天说一个细分的需求,在模型中,或者使用laravel提供的EloquentORM功能,构造查询语句时,返回位于两个指定的日期之间的条目。应该怎么写?本文通过几个例子,为大家梳理一下。学习时...
- 一文由浅入深带你完全掌握MySQL的锁机制原理与应用
-
本文将跟大家聊聊InnoDB的锁。本文比较长,包括一条SQL是如何加锁的,一些加锁规则、如何分析和解决死锁问题等内容,建议耐心读完,肯定对大家有帮助的。为什么需要加锁呢?...
- 验证Mysql中联合索引的最左匹配原则
-
后端面试中一定是必问mysql的,在以往的面试中好几个面试官都反馈我Mysql基础不行,今天来着重复习一下自己的弱点知识。在Mysql调优中索引优化又是非常重要的方法,不管公司的大小只要后端项目中用到...
- MySQL索引解析(联合索引/最左前缀/覆盖索引/索引下推)
-
目录1.索引基础...
- 你会看 MySQL 的执行计划(EXPLAIN)吗?
-
SQL执行太慢怎么办?我们通常会使用EXPLAIN命令来查看SQL的执行计划,然后根据执行计划找出问题所在并进行优化。用法简介...
- MySQL 从入门到精通(四)之索引结构
-
索引概述索引(index),是帮助MySQL高效获取数据的数据结构(有序),在数据之外,数据库系统还维护者满足特定查询算法的数据结构,这些数据结构以某种方式引用(指向)数据,这样就可以在这些数据结构...
- mysql总结——面试中最常问到的知识点
-
mysql作为开源数据库中的榜一大哥,一直是面试官们考察的重中之重。今天,我们来总结一下mysql的知识点,供大家复习参照,看完这些知识点,再加上一些边角细节,基本上能够应付大多mysql相关面试了(...
- mysql总结——面试中最常问到的知识点(2)
-
首先我们回顾一下上篇内容,主要复习了索引,事务,锁,以及SQL优化的工具。本篇文章接着写后面的内容。性能优化索引优化,SQL中索引的相关优化主要有以下几个方面:最好是全匹配。如果是联合索引的话,遵循最...
- MySQL基础全知全解!超详细无废话!轻松上手~
-
本期内容提醒:全篇2300+字,篇幅较长,可搭配饭菜一同“食”用,全篇无废话(除了这句),干货满满,可收藏供后期反复观看。注:MySQL中语法不区分大小写,本篇中...
- 深入剖析 MySQL 中的锁机制原理_mysql 锁详解
-
在互联网软件开发领域,MySQL作为一款广泛应用的关系型数据库管理系统,其锁机制在保障数据一致性和实现并发控制方面扮演着举足轻重的角色。对于互联网软件开发人员而言,深入理解MySQL的锁机制原理...
- Java 与 MySQL 性能优化:MySQL分区表设计与性能优化全解析
-
引言在数据库管理领域,随着数据量的不断增长,如何高效地管理和操作数据成为了一个关键问题。MySQL分区表作为一种有效的数据管理技术,能够将大型表划分为多个更小、更易管理的分区,从而提升数据库的性能和可...
- MySQL基础篇:DQL数据查询操作_mysql 查
-
一、基础查询DQL基础查询语法SELECT字段列表FROM表名列表WHERE条件列表GROUPBY分组字段列表HAVING分组后条件列表ORDERBY排序字段列表LIMIT...
- MySql:索引的基本使用_mysql索引的使用和原理
-
一、索引基础概念1.什么是索引?索引是数据库表的特殊数据结构(通常是B+树),用于...
- 一周热门
-
-
C# 13 和 .NET 9 全知道 :13 使用 ASP.NET Core 构建网站 (1)
-
程序员的开源月刊《HelloGitHub》第 71 期
-
详细介绍一下Redis的Watch机制,可以利用Watch机制来做什么?
-
假如有100W个用户抢一张票,除了负载均衡办法,怎么支持高并发?
-
Java面试必考问题:什么是乐观锁与悲观锁
-
如何将AI助手接入微信(打开ai手机助手)
-
redission YYDS spring boot redission 使用
-
SparkSQL——DataFrame的创建与使用
-
一文带你了解Redis与Memcached? redis与memcached的区别
-
如何利用Redis进行事务处理呢? 如何利用redis进行事务处理呢英文
-
- 最近发表
- 标签列表
-
- git pull (33)
- git fetch (35)
- mysql insert (35)
- mysql distinct (37)
- concat_ws (36)
- java continue (36)
- jenkins官网 (37)
- mysql 子查询 (37)
- python元组 (33)
- mybatis 分页 (35)
- vba split (37)
- redis watch (34)
- python list sort (37)
- nvarchar2 (34)
- mysql not null (36)
- hmset (35)
- python telnet (35)
- python readlines() 方法 (36)
- munmap (35)
- docker network create (35)
- redis 集合 (37)
- python sftp (37)
- setpriority (34)
- c语言 switch (34)
- git commit (34)