前言
Python Imaging Library ( PIL ) 给 Python 增加了图像处理能力。
这个库提供了广泛的文件格式支持,高效的内部展现,以及十分强大的图像处理能力。
图像存储
PIL 设计用于图像归档和图像批量处理,你可以使用它建立缩略图,转换格式,打印图片等等。
图像显示
提供show()方法,可以保存图像到磁盘并显示。
图像处理
这个库包含了基本的图像处理功能,包括点操作,使用内置卷积内核过滤,色彩空间转换。
这个库还支持更改图像大小、旋转、自由变换。
有一个直方图方法允许你统计图像,这可以用于对比度增强和全局统计分析。
以此图为例
使用Image类打开图片
1、从文件加载图像,使用Image.open()函数
from PIL import Image
img = Image.open("tu9.jpeg")
加载成功返回一个Image对象,我们可以使用matplotlib库来展示图片。
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open("tu9.jpeg")
plt.imshow(img)
plt.show()
图像展示如下:
2、使用ImageFilter滤镜处理图片
from PIL import Image,ImageFilter
import matplotlib.pyplot as plt
img = Image.open('tu7.jpeg')
filters=[
ImageFilter.BLUR,
ImageFilter.CONTOUR,
ImageFilter.EDGE_ENHANCE,
ImageFilter.EMBOSS,
ImageFilter.SHARPEN,
ImageFilter.SMOOTH,
]
#行和列
row=2
col=3
_,axes=plt.subplots(row,col,figsize=(20,20))#创建2行3列的大画布
for i in range(row): #i取0和1
for j in range(col): #j取0,1,2
index=j+col*i
img_temp=img.filter(filters[index])
axes[i][j].imshow(img_temp)
axes[i][j].set_title(filters[index].name)
plt.show()
3、save()方法保存图片
要保存文件,使用 Image 类的 save() 方法。保存文件的时候文件名变得重要了。除非你指定格式,否则这个库将会以文件名的扩展名作为格式保存。
这里在保存的时候用滤镜的名字命名保存的图片。
#保存滤镜处理后的图片
for i in range(len(filters)):
img_temp=img.filter(filters[i])
img_temp.save("maopian_{}.jpg".format(i))
当然也可以指定保存的文件格式。
img_temp.save("maopian_{}.jpg".format(i),'JPEG')
二、图像变换
导入库,打开图片,图示创建画布。
from PIL import Image
import matplotlib.pyplot as plt
img=Image.open("tu9.jpeg")
# 创建画布2*4
_,axes=plt.subplots(2,4,figsize=(25,25))
# print(_,"\n",axes)
axes[0][0].imshow(img)
axes[0][0].set_title("orginal")
1.缩略图
# 缩略图
_img=img.copy() #复制图片,因为缩略图会对原图进行改变
newsize=(50,50)#设置新图片的一个大小 (元组)
_img.thumbnail(newsize) #thumbnail缩略图
axes[0][1].imshow(_img)
axes[0][1].set_title("thumbnail")
2.缩放与拉伸
#缩放与拉伸
newsize=(50,150)
img_resize=img.resize(newsize)
axes[0][2].imshow(img_resize)
axes[0][2].set_title("resize")
3、裁剪
#剪裁
#img.width//2,img.height//2是获取图片的中心点的坐标
img_crop=img.crop((100,100,img.width//2+100,img.height//2+100))
axes[0][3].imshow(img_crop)
axes[0][3].set_title("crop")
4、旋转
#旋转
img_rotate=img.rotate(45)
axes[1][0].imshow(img_rotate)
axes[1][0].set_title("rotate")
img_rotate_2=img.rotate(45,expand=True)#扩展画布
axes[1][1].imshow(img_rotate_2)
axes[1][1].set_title("rotate_expend")
5、翻转
#水平翻转
img_flip_left_right=img.transpose(Image.FLIP_LEFT_RIGHT)
axes[1][2].imshow(img_flip_left_right)
axes[1][2].set_title("flip_horizontal")
#垂直翻转
img_flip_top_bottom=img.transpose(Image.FLIP_TOP_BOTTOM)
axes[1][3].imshow(img_flip_top_bottom)
axes[1][3].set_title("flip_vertical")
6、展示图片
plt.show()