百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

Python图像处理神器!Pillow库从入门到精通,这教程太全了

wptr33 2025-07-23 18:43 5 浏览

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的核心功能,并将其应用到实际项目中,如图片处理工具、网站图像处理、验证码生成等场景。

#py thon##python自学##图像##ai技术教程##在头条记录我的2025#

相关推荐

HIVE 窗口函数详解(hive常用开窗函数)

什么是窗口函数窗口函数是SQL中一类特别的函数。和聚合函数相似,窗口函数的输入也是多行记录。不同的是,聚合函数的作用于由GROUPBY子句聚合的组,而窗口函数则作用于一个窗口,这里,窗口...

SQL高效使用20招:数据分析师必备技巧

基础优化技巧善用EXPLAIN分析执行计划EXPLAINSELECT*FROMordersWHEREorder_date>'2024-01-01';...

答记者问之 - Redis 的高效架构与应用模式解析

问:极客程序员你好,请帮我讲一讲redis答:redis主要涉及以下核心,我来一一揭幕Redis的高效架构与应用模式解析...

MySQL通过累计求新增(mysql新增表字段语句)

前两天的那篇内容《MySQL递归实现单列分列成多行》...

一文讲懂SQL窗口函数 大厂必考知识点

大家好,我是宁一。今天是我们的第24课:窗口函数。...

圣诞快乐:用GaussDB T 绘制一颗圣诞树,兼论高斯数据库语法兼容

转眼就是圣诞的节日,祝大家节日快乐。用GaussDBT(也就是GaussDB100)绘制一棵圣诞树,纯国产,更喜庆。话不多说,上图:SQL如下:SELECTCASEWHENENMOTE...

Minitab:功能强大的质量管理、统计分析及统计图形软件

一、Minitab简介Minitab软件是为质量改善、教育和研究应用领域提供统计软件和服务的先导,是全球领先的质量管理和六西格玛实施软件工具及持续质量改进的良好工具软件,她具有强大的功能和简易的可视化...

如何熟练使用SQL查询(如何熟练使用sql查询内容)

要熟练使用SQL查询(StructuredQueryLanguage),你需要系统地从语法入门,到实战练习,再到性能优化与多表查询的掌握。下面是一条循序渐进、实战驱动的学习路径:第一阶段:S...

SAP SE38如何在多个系统间同步代码

上一篇文章写了如何在多个系统之间同步开发对象:多套SAPERP之间一键同步ABAP开发内容,有兄弟问有没有简单办法同步SE38程序代码的,因为使用请求的方式同步代码有点小题大做了。...

Python | 垂直模态分解(phython垂直输出)

...

技术栈:刷了百道SQL题,还是不会用?你应该这样补短板

这是来自用户的提问,也是很多人遇到的困惑:...

mysql窗口函数为了解决更加复杂的问题

为了解决复杂问题的窗口函数我们先讲一下窗口函数是什么窗口和普通的函数作用相同在不同列上进行查询和返回比如我们有如下的表...

MariaDB开窗函数(开窗函数 mysql)

在使用GROUPBY子句时,总是需要将筛选的所有数据进行分组操作,它的分组作用域是整张表。分组以后,为每个组只返回一行。而使用基于窗口的操作,类似于分组,但却可以对这些"组"(即窗口...

一文掌握 DuckDB 时间序列分析:窗口函数实战详解

...

一篇文章搞定MySQL中的窗口函数(mysql常用的窗口函数)

我是孙斌,北理数学系毕业,分享数据分析相关知识,点击右上角“关注”,学习更多数据分析知识。在MySQL中,分组groupby一般和聚合函数连用,如groupby+sum,这样能够得到每个组的总和,...