Pillow 是 PIL 的替代版本。 由于PIL仅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基础上创建了兼容的版本。 新版本的名字叫Pillow,支持最新的Python 3.x,并加入了许多新特性。
PIL 软件包提供了基本的图像处理功能, 如:改变图像大小,旋转图像,图像格式转换,颜色空间转换,图像增强,直方图处理,插值和滤波等等。
安装Pillow 使用命令:
# pip install pillow
可以直接安装,也可以使用 Anaconda 安装。
from PIL import Image
注意,导入pillow模块用的是PIL,而不是pillow。
Pillow
提供 ImageColor.getcolor()
函数,所以不必记住想用的顔色的 RGBA
值。
该函数接受一个颜色名称字符串作为第一个参数,字符串 'RGBA'
作为第二个参数,
返回一个 RGBA
元组。
要了解该函数的工作方式,就在交互式环境中输入以下代码:
from PIL import ImageColor
ImageColor.getcolor('red', 'RGBA')
(255, 0, 0, 255)
ImageColor.getcolor('RED', 'RGBA')
(255, 0, 0, 255)
ImageColor.getcolor('Black', 'RGBA')
(0, 0, 0, 255)
ImageColor.getcolor('chocolate', 'RGBA')
(210, 105, 30, 255)
ImageColor.getcolor('CornflowerBlue', 'RGBA')
(100, 149, 237, 255)
首先,需要从 PIL
导入 ImageColor
模块 (不是从 Pillow
,稍后就会明白为什么)。
传递给 ImageColor.getcolor()
的颜色名称字符串是不区分大小写的,
所以传入red
和传入 RED
将得到同样的 RGBA
元组。
还可以传递更多的不常见的颜色名称,如 chocolate
和 Cornflower Blue
。
Pillow
支持大量的颜色名称,从 aliceblue
, 至 whitesmoke
。
在 http://nostarch.com/automatestuff/ 的资源中,可以找到超过100种标准颜色名称的完整列表。
import matplotlib.pyplot as plt
image = Image.open('/data/demo/L1020120.JPG')
print(image.format, image.size, image.mode)
JPEG (1000, 734) RGB
plt.imshow(image)
plt.show()
image_path='/data/demo/L1020120.JPG'
outfile = "./xx_img2_2.png"
try:
Image.open(image_path).save(outfile)
except IOError:
print("cannot convert", image_path)
image=Image.open(outfile)
print(image.format, image.size, image.mode)
PNG (1000, 734) RGB
image_path = '/data/demo/L1020120.JPG'
size
为缩略图宽长元组,先准备好 size
的值。
为了保证图片不失真变形,当指定了图片的宽和高时,pillow
会以宽度为准进行缩小。
size = (256, 256)
outfile = "./xx_img1_1.png"
im = Image.open(image_path)
print(im.mode,im.size,im.format)
RGB (1000, 734) JPEG
使用 thumbnail()
方法,将size
参数传入,将图片缩小为设置的尺寸。
im.thumbnail(size)
im.convert('RGB')
im.save(outfile)
如果上面的缩略图无法直接保存,需要进行模式的转换,不然会出现如下问题:
无法将RGBA模式写入JPEG格式。
img=Image.open(outfile)
print(img.mode,img.size,img.format)
RGB (256, 188) PNG