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)  # 增加亮度
相关推荐
Derrick__112 天前
Python常用三方模块——Pillow
开发语言·python·pillow
eqwaak017 天前
Pillow高级实战案例:图像处理的进阶应用
开发语言·python·科技·语言模型·pillow
爱蹦跶的精灵17 天前
降级版本Pillow解决freetypefont has no attribute getsize问题
python·pillow
eqwaak018 天前
Python Pillow库详解:图像处理的瑞士军刀
开发语言·图像处理·python·语言模型·pillow
是乐谷1 个月前
Python图片转WebP常用库推荐:Pillow、Wand、cv2
大数据·运维·开发语言·人工智能·python·开源·pillow
WSSWWWSSW1 个月前
Python Imaging Library (PIL) 全面指南:PIL高级图像处理-分割与颜色空间转换
图像处理·python·计算机视觉·pillow
WSSWWWSSW2 个月前
Jupyter Notebook 中高效处理和实时展示来自 OpenCV 和 Pillow 的图像数据探究
opencv·jupyter·pillow
万粉变现经纪人3 个月前
如何解决pip安装报错ModuleNotFoundError: No module named ‘pillow’问题
python·pycharm·beautifulsoup·pandas·pillow·pip·策略模式
旷世奇才李先生3 个月前
Pillow 安装使用教程
深度学习·microsoft·pillow
微信公众号:AI创造财富4 个月前
构建 docket uable to prepar context: path “.“ not found
python·plotly·flask·pillow·ipython·tornado