1 PIL:python图像处理库
(1)PIL最重要的模块为Image,读取一张图像。
from PIL import Image
pil_im = Image.open('example.jpg')
(2)对读入的图像进行转换,使用Convert()方法
pil_im = Image.open('example.jpg').convert(‘L’)
2 对图像格式进行转换,使用save()方法
from PIL import Image
import os
for infile in filelist:
#PIL的Open()函数创建PIL图像对象
outfile = os.path.splitext(infile) + ".jpg"
if infile != outfile:
#save()保存为指定的文件名的文件
Image.open(infile).save(outfile)
except IOError:
print("cannot convert", infile)
3 对大量图片进行处理,通过创建一个图像的文件名列表,下面建立一个imtools.py文件,存储经常使用的图像操作。
import os
def get_imlist(path):
"""返回path中所有JPG格式的图像"""
return [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.jpg')]
4 创建缩略图,使用thumbnail()方法接受一个元组参数(指定生成缩略图的大小),将图像转换成符合元组参数大小指定的缩略图。如创建最长边为128像素的缩略图。
pil_im.thumbnail((128, 128))
5 复制,粘贴图像区域,使用crop()方法裁剪,传入四元组作为参数,坐标依次是(上,下,左,右),然后使用paste()方法进行粘贴。
#裁剪
box = (100, 100, 100, 100)
region = pil_im.crop(box)
#旋转180度,放回去
region = region.transpose(Image.ROTATE_180)
pil_im.paste(region, box)
6 调整尺寸和旋转,调用resize()方法,参数是一个元组,指定新图像的大小。
out = pil_im.resize((128, 128))
#逆时针旋转,使用rotate()方法
out = pil_im.rotate(45)