1.1.6 Pillow读写图像文件
PIL即Python Imaging Library,曾是Python事实上的图像处理标准库。尽管PIL功能强大,API简单易用,但是PIL仅支持到Python 2.7就停止更新。Alex Clark与众多志愿者在PIL基础上创建了兼容版本Pillow,又加入了许多新特性,支持最新Python 3.x。Pillow的Image模块提供了PIL图像类(PIL Image Class),其中用于图像文件读写的函数为Image.open()、Image.save()。
以下示例程序读入一幅索引图像(indexed image,或palette image),将其转换为灰度图像、RGB真彩色图像并保存。
#Pillow函数读写图像文件
#导入用到的包及模块
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
#从当前工作目录下的imagedata子目录中读入一幅索引图像
im = Image.open('./imagedata/trees.tif')
#调用Image对象成员函数将其转换为灰度图像
imgray=im.convert('L') #结果仍为PIL图像类
#调用Image对象成员函数将其转换为RGB真彩色图像,结果仍为PIL图像类
imrgb=im.convert('RGB')
imrgb.save('treesrgb.jpg') #保存图像
#显示图像的格式、高、宽尺寸以及图像类型
print(im.format, im.size, im.mode)
#将图像转换为ndarray多维数组,得到引图像的像素颜色索引值数组
img = np.asarray(im)
#显示结果
plt.figure(figsize=(16,6))
#显示原索引图像
plt.subplot(1,4,1); plt.imshow(im)
plt.title('trees, original indexd image'); plt.axis('off')
#采用Matplotlab内嵌调色板显示读入的索引图像数据
plt.subplot(1,4,2); plt.imshow(img, cmap = 'viridis', vmin=0,vmax=255)
plt.title('trees, indexd image, another colormap'); plt.axis('off')
#显示转换后的RGB真彩色图像
plt.subplot(1,4,3); plt.imshow(imrgb)
plt.title('trees, RGB color image') ;plt.axis('off')
#显示显示转换后的灰度图像
plt.subplot(1,4,4); plt.imshow(imgray, cmap='gray', vmin=0,vmax=255)
plt.title('trees, gray image'); plt.axis('off')
plt.show()
#---------------------------------------
函数Image.open()返回值不是NumPy的ndarray型数组,而是一个PIL Image对象,它提供了图像文件的属性值、以及对图像进行处理的方法函数。读取索引图像时,可得到像素颜色索引值数组和调色板(颜色表)数组(palette,又称colormap)。例如,PIL image对象的mode属性,是一个字符串变量,给出了所读取的图像类型。