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

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

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

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#

相关推荐

oracle数据导入导出_oracle数据导入导出工具

关于oracle的数据导入导出,这个功能的使用场景,一般是换服务环境,把原先的oracle数据导入到另外一台oracle数据库,或者导出备份使用。只不过oracle的导入导出命令不好记忆,稍稍有点复杂...

继续学习Python中的while true/break语句

上次讲到if语句的用法,大家在微信公众号问了小编很多问题,那么小编在这几种解决一下,1.else和elif是子模块,不能单独使用2.一个if语句中可以包括很多个elif语句,但结尾只能有一个...

python continue和break的区别_python中break语句和continue语句的区别

python中循环语句经常会使用continue和break,那么这2者的区别是?continue是跳出本次循环,进行下一次循环;break是跳出整个循环;例如:...

简单学Python——关键字6——break和continue

Python退出循环,有break语句和continue语句两种实现方式。break语句和continue语句的区别:break语句作用是终止循环。continue语句作用是跳出本轮循环,继续下一次循...

2-1,0基础学Python之 break退出循环、 continue继续循环 多重循

用for循环或者while循环时,如果要在循环体内直接退出循环,可以使用break语句。比如计算1至100的整数和,我们用while来实现:sum=0x=1whileTrue...

Python 中 break 和 continue 傻傻分不清

大家好啊,我是大田。...

python中的流程控制语句:continue、break 和 return使用方法

Python中,continue、break和return是控制流程的关键语句,用于在循环或函数中提前退出或跳过某些操作。它们的用途和区别如下:1.continue(跳过当前循环的剩余部分,进...

L017:continue和break - 教程文案

continue和break在Python中,continue和break是用于控制循环(如for和while)执行流程的关键字,它们的作用如下:1.continue:跳过当前迭代,...

作为前端开发者,你都经历过怎样的面试?

已经裸辞1个月了,最近开始投简历找工作,遇到各种各样的面试,今天分享一下。其实在职的时候也做过面试官,面试官时,感觉自己问的问题很难区分候选人的能力,最好的办法就是看看候选人的github上的代码仓库...

面试被问 const 是否不可变?这样回答才显功底

作为前端开发者,我在学习ES6特性时,总被const的"善变"搞得一头雾水——为什么用const声明的数组还能push元素?为什么基本类型赋值就会报错?直到翻遍MDN文档、对着内存图反...

2023金九银十必看前端面试题!2w字精品!

导文2023金九银十必看前端面试题!金九银十黄金期来了想要跳槽的小伙伴快来看啊CSS1.请解释CSS的盒模型是什么,并描述其组成部分。...

前端面试总结_前端面试题整理

记得当时大二的时候,看到实验室的学长学姐忙于各种春招,有些收获了大厂offer,有些还在苦苦面试,其实那时候的心里还蛮忐忑的,不知道自己大三的时候会是什么样的一个水平,所以从19年的寒假放完,大二下学...

由浅入深,66条JavaScript面试知识点(七)

作者:JakeZhang转发链接:https://juejin.im/post/5ef8377f6fb9a07e693a6061目录...

2024前端面试真题之—VUE篇_前端面试题vue2020及答案

添加图片注释,不超过140字(可选)...

今年最常见的前端面试题,你会做几道?

在面试或招聘前端开发人员时,期望、现实和需求之间总是存在着巨大差距。面试其实是一个交流想法的地方,挑战人们的思考方式,并客观地分析给定的问题。可以通过面试了解人们如何做出决策,了解一个人对技术和解决问...