Python图像处理神器!Pillow库从入门到精通,这教程太全了
wptr33 2025-07-23 18:43 17 浏览
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的核心功能,并将其应用到实际项目中,如图片处理工具、网站图像处理、验证码生成等场景。
相关推荐
- Python字符串终极指南!单引号、双引号、三引号区别全解析
-
导语:Python中字符串(str)是最核心的数据类型!无论你是输出"HelloWorld"还是处理用户数据,都离不开它。今天彻底讲清字符串的三大定义方式及其核心区别,新手必看!...
- python 字符串的定义和表示_python字符串的用法
-
在Python中,字符串是一序列字符的集合。定义一个字符串可以使用单引号或双引号括起来的字符序列。...
- 简单的python-熟悉字符串相关的操作
-
str.py:#-*-coding:utf-8-*-#测试函数deff():#字符串使用单引号定义s1='test'print(s...
- Python初学者:3招搞定长字符串逐行读取,代码超简单
-
刚学Python的小伙伴,是不是遇到过这种尴尬情况?拿到一段老长的多行字符串——比如从文档里复制的日志、一段带换行的文章,想一行一行处理,如果直接打印全堆在一起,手动切又怕漏行,咋整啊?别慌!今天就给...
- Python 字符串_python字符串型怎么表达
-
除了数字,Python还可以操作字符串。字符串的形式是单引号('......')双引号(''.........'')或三个单引号(''&...
- 贴身口语第二关:请求帮忙、道歉、指路、接受礼物
-
02-@askforhelp请求协助1.F:Excuseme.Canyouhelpme?M:Yes,whatcanIdoforyou?...
- NBA赛季盘点之九大装逼&炫技时刻:“歪嘴战神”希罗领衔
-
欢迎大家来到直播吧NBA赛季盘点,历经许多波折,2019-20赛季耗时整整一年才圆满收官。魔幻的一年里有太多的时刻值得我们去铭记,赛场上更是不乏球员们炫技与宣泄情绪的装逼时刻,本期盘点就让我们来回顾一...
- 一手TTS-2语音合成模型安装教程及实际使用
-
语音合成正从云端调用走向本地部署,TTS-2模型作为开源语音生成方案之一,正在被越来越多开发者尝试落地。本篇文章从环境配置到推理调用,详尽拆解TTS-2的安装流程与使用技巧,为语音产品开发者提供...
- 网友晒出身边的巨人 普通人站一旁秒变“霍比特人”
-
当巨人遇到霍比特人,结果就是“最萌身高差”。近日网友们晒出了身边的巨人,和他们站在一起,普通人都变成了“霍比特人”。CanYouTellWho'sRelated?TheDutchGiant...
- 分手后我们还能做朋友吗?_分手后我们还能做朋友吗
-
Fewrelationshipquestionsareaspolarizingaswhetherornotyoushouldstayfriendswithanex.A...
- 如何用C语言实现Shellcode Loader
-
0x01前言之前github找了一个基于go的loader,生成后文件大小6M多,而且细节不够了解,一旦被杀,都不知道改哪里,想来还是要自己写一个loader...
- 微星Z490如何装Windows10系统以及怎么设 BIOS
-
小晨儿今天给大家讲一下msi微星Z490重怎样装系统以及怎么设置BIOS。一、安装前的准备工作1、一、安装前的准备工作1、备份硬盘所有重要的文件(注:GPT分区转化MBR分区时数据会丢失)2...
- 超实用!互联网软件开发人员不可不知的 Git 常用操作命令
-
在互联网软件开发的协作场景中,Git是不可或缺的版本控制工具。掌握其核心命令,能让代码管理效率大幅提升。本文精选Git高频实用命令,结合场景化说明,助你快速上手。仓库初始化与克隆...
- AI项目的持续集成持续部署实践_ai 项目
-
在独立开发AI工具的过程中,笔者逐步实践了一套高效的软件项目持续集成与持续部署(CI/CD)流程。这套流程以Git、GitHub和Vercel为核心,实现了从代码提交到生产环境上线的全链路自动化。这篇...
- 总结几个常用的Git命令的使用方法
-
1、Git的使用越来越广泛现在很多的公司或者机构都在使用Git进行项目和代码的托管,Git有它自身的优势,很多人也喜欢使用Git。...
- 一周热门
- 最近发表
- 标签列表
-
- 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)