Python Pillow (PIL) 库简介

Python Pillow (PIL) 库简介

Pillow是Python Imaging Library (PIL) 的一个活跃的分支。它添加了对许多文件格式的支持,并提供了强大的图像处理和图形功能。下面是Pillow库的一些基本用法。

安装Pillow

在使用Pillow之前,你需要先安装它。可以通过pip安装:

python 复制代码
pip install Pillow

打开、保存和显示图像

使用Pillow,你可以很容易地打开、处理和保存各种类型的图像。

python 复制代码
from PIL import Image

# 打开图像
image = Image.open('example.jpg')

# 显示图像
image.show()

# 保存图像
image.save('new_example.jpg')

图像操作

Pillow可以用于基本图像操作,例如旋转、缩放和裁剪。

python 复制代码
# 旋转图像
rotated = image.rotate(90)

# 缩放图像
resized = image.resize((100, 100))

# 裁剪图像
cropped = image.crop((0, 0, 50, 50))

图像滤镜

Pillow还支持多种内置滤镜,如模糊、锐化等。

python 复制代码
from PIL import ImageFilter

# 应用模糊滤镜
blurred = image.filter(ImageFilter.BLUR)

# 应用锐化滤镜
sharpened = image.filter(ImageFilter.SHARPEN)

绘制和文字

你还可以使用Pillow来绘制图形或在图像上添加文字。

python 复制代码
from PIL import ImageDraw, ImageFont

draw = ImageDraw.Draw(image)
font = ImageFont.load_default()

# 绘制简单的图形
draw.rectangle(((0, 0), (50, 50)), fill="blue")

# 添加文字
draw.text((10, 10), "Hello World", font=font, fill="green")

图像色彩变换

Pillow可以进行色彩空间转换和调整。

python 复制代码
# 转换为灰度图
greyscale = image.convert('L')

# 色彩增强
from PIL import ImageEnhance
enhancer = ImageEnhance.Brightness(image)
brighter = enhancer.enhance(2)  # 增加亮度
相关推荐
恣艺4 小时前
Python 图像处理实战:Pillow 与 OpenCV 从入门到精通
图像处理·python·pillow
向日的葵0068 天前
阿里云OSS从0到1实战:为宠物收养系统打造图片上传功能
python·阿里云·云计算·pillow·fastapi·宠物
Dxy123931021614 天前
Python Pillow库:`img.format`与`img.mode`的区别详解
开发语言·python·pillow
yuanpan14 天前
Python + Pillow 实战:开发一个图片批量格式转换工具
python·microsoft·pillow
万粉变现经纪人1 个月前
如何解决 import aiohttp ModuleNotFoundError: No module named ‘aiohttp’
python·scrapy·beautifulsoup·aigc·pillow·pip·httpx
智算菩萨2 个月前
【Python图像处理】5 Pillow图像处理与格式转换
图像处理·python·pillow
nFBD29OFC2 个月前
pillow - 图像处理的瑞士军刀
图像处理·人工智能·pillow
万粉变现经纪人2 个月前
如何解决 pip install pillow-simd 报错 需要 AVX2/特定编译器 支持 问题
python·scrapy·beautifulsoup·aigc·pandas·pillow·pip
MoRanzhi12032 个月前
Pillow 图像分割、切片与拼接处理
图像处理·人工智能·python·计算机视觉·pillow·图像拼接·网格分块
MoRanzhi12032 个月前
pillow 图像合成、透明叠加与蒙版处理
python·计算机视觉·pillow·图片处理·图像合成·透明叠加·多图层叠加