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)  # 增加亮度
相关推荐
万粉变现经纪人6 天前
如何解决 pip install pillow-simd 报错 需要 AVX2/特定编译器 支持 问题
python·scrapy·beautifulsoup·aigc·pandas·pillow·pip
MoRanzhi120313 天前
Pillow 图像分割、切片与拼接处理
图像处理·人工智能·python·计算机视觉·pillow·图像拼接·网格分块
MoRanzhi120313 天前
pillow 图像合成、透明叠加与蒙版处理
python·计算机视觉·pillow·图片处理·图像合成·透明叠加·多图层叠加
MoRanzhi120314 天前
Pillow 图像算术运算与通道计算
图像处理·人工智能·python·计算机视觉·pillow·图像差异检测·图像算术运算
MoRanzhi120314 天前
Pillow 灰度化、二值化与阈值处理
图像处理·python·pillow·二值化·图像预处理·阈值处理·灰度化
MoRanzhi120314 天前
Pillow 图像颜色模式与颜色空间转换
图像处理·python·数学建模·pillow·颜色空间转换·颜色模式·图像通道
MoRanzhi120315 天前
Pillow 图像滤波、卷积与边缘处理
图像处理·python·计算机视觉·pillow·卷积·边缘检测·图像滤波
代码小书生1 个月前
pillow,一个实用的 Python 库!
开发语言·python·pillow
开源技术2 个月前
Python Pillow 优化,打开和保存速度最快提高14倍
开发语言·python·pillow