一、PIL概述
PIL(Python Image Library)库是Python语言的第三方库,需要通过pip工具安装。安装PIL库的方法如下,需要注意,安装库的名字是pillow。
:\>pip install pillow #或者 pip3 install pillow
PIL库支持图像储存、显示和处理,他能够处理几乎所有图片格式,可以完成对图像的缩放、剪裁、叠加以及向图像添加线条、图像和文字等操作。
PIL库主要可以实现图像归档和图像处理两方面功能需求。
(1)图像归档:对图像进行批处理、生成图像预览、图像格式转换等。
(2)图像处理:图像基本处理、像素处理、颜色处理等。
根据功能不同,PIL库共包括21个与图片相关的类,这些类可以被看作是子库或PIL库中的模块,子库列表如下:
Image、ImageChops、ImageColor、ImageCrackCode、ImageDraw、Image Enhance、ImageFile、ImageFileIO、ImageFilter、Image Font、ImageGL、ImageGrab、Imagemath、ImageOps、ImagePalette、ImagePath、ImageQt、ImageSequence、ImageStat、ImageTk、ImageWin
二、缩略图制作
代码
from PIL import Image im = Image.open("pg1.jpg") #此处为打开的图片名,注意将要操作的图片放置到与程序相同的目录下 im.thumbnail((128,128)) #此处的128,128是指略缩图的像素尺寸为128*128,可根据自身需要进行修改 im.save("pg2.jpg","JPEG") #此处两个双引号分别表示略缩图的文件名和略缩图格式
对比图:
三、改变颜色,轮廓,浮雕操作
改变颜色代码:
from PIL import Image im = Image.open("pg1.jpg") #打开目标图片 r,g,b=im.split() om = Image.merge("RGB",(b,g,r))#在(b,g,r)将三个字母进行交换得到效果图 om.save(‘pg.jpg‘) #储存文件名
对比:
轮廓代码:
from PIL import Image from PIL import ImageFilter im=Image.open("pg1.jpg") om=im.filter(ImageFilter.CONTOUR) om.save("pg3.jpg") om.show()
对比
浮雕代码:
from PIL import Image from PIL import ImageFilter im=Image.open("pg1.jpg") om=im.filter(ImageFilter.EMBOSS) om.save("pg4.jpg") om.show()
对比
四、gif逐帧分解
代码:
from PIL import Image im = Image.open(‘可爱.gif‘) #打开待处理的图片 try: im.save(‘picframe{:02d}.png‘.format(im.tell())) while True: im.seek(im.tell()+1) im.save(‘picframe{:02d}.png‘.format(im.tell()))#以png格式储存动图的每一帧 except: print("处理结束") #提示程序的处理进度
效果图:
原图:
原文:https://www.cnblogs.com/yangsenhan/p/12724633.html