PIL是Python著名的图像处理库。尽管PIL无法像OpenCV那样实现高级图像处理功能,比如:面部识别、滤镜等,但PIL可以更加高效执行简单的图像处理,例如:调整大小(缩放),旋转和修剪(局部切除)等操作,并且代码更加简洁。
PIL的安装
图像文件的读取
今天我们要用到的是PIL模块提供resize()函数,该函数就是调整图像大小的方法。
只需要将一个元组(width, height)传递给resize()函数,PIL就会把图像处理好。
例如下面的程序:
from PIL import Image
img = Image.open('data/src/lena_square.png')
img_resize = img.resize((256, 256))
img_resize.save('data/dst/lena_pillow_resize_nearest.jpg')
img_resize_lanczos = img.resize((256, 256), Image.LANCZOS)
img_resize_lanczos.save('data/dst/lena_pillow_resize_lanczos.jpg')
在以上示例中,新的图像尺寸固定为(256, 256)。如果想基于原始图像的尺寸进行调整,请执行以下操作:
img_resize = img.resize((int(img.width / 2), int(img.height / 2)))
img_resize_lanczos.save('data/dst/lena_pillow_resize_half.jpg')
因为最终的图像尺寸应该为整数,所以我们使用了int()将取半后的尺寸取整。
如果想对指定目录的所有照片进行resize操作,可以使用glob库中的glob()函数,或者os.path的walk()函数,对指定目录进行遍历。
取得目标文件夹中文件的路径字符串,再使用resize()进行图像尺寸调整,最后是通过save()函数保存为新文件名。
仅提取带有扩展名的文件的示例代码jpg如下:
import os
import glob
from PIL import Image
files = glob.glob('./data/temp/images/*.jpg')
for f in files:
img = Image.open(f)
img_resize = img.resize((int(img.width / 2), int(img.height / 2)))
title, ext = os.path.splitext(f)
img_resize.save(title + '_half' + ext)
也可以使用列表读取多种格式图像文件:
files = glob.glob('./data/temp/images/*')
for f in files:
title, ext = os.path.splitext(f)
if ext in ['.jpg', '.png']:
img = Image.open(f)
img_resize = img.resize((int(img.width / 2), int(img.height / 2)))
img_resize.save(title + '_half' + ext)
如果要调整Pillow支持的所有图像文件的大小,而不是按扩展名提取,请使用try ... except ...处理异常。
正式程序如下:
files = glob.glob('./data/temp/images/*')
for f in files:
try:
img = Image.open(f)
img_resize = img.resize((int(img.width / 2), int(img.height / 2)))
title, ext = os.path.splitext(f)
img_resize.save(title + '_half' + ext)
except OSError as e:
pass
你可以根据自己的实际情况调整:glob()中的路径;
resize()中的宽和高的数字;
save()函数只是在原文件名后加了_half,你可根据需要改变文件名。