参考:https://www.cnblogs.com/meitian/p/3699223.html
之前一直是用opencv对图片进行读取、显示等操作,后来发现Python自带的库PIL也可以完成相同的操作,至于两者的区别,后边再研究,本文总结PIL常用的方法函数。在使用之前,要先导入库
from PIL import Image
1 打开图片
img=Image.open("kobe.jpg")
注:有些图片名称是包含中文的,就需要在“”前加上u,例:img=Image.open(u"阿布.jpg")
2 显示图片
img.show()
3 输出图片信息
print img.mode,img.size,img.format
结果为 RGB (508, 493) JPEG
4 保存图片
img.save("img1.png","png")
说明:img为一个图片,存为一个名叫img1的图片,格式为png。后面的png不写也可以,直接按照文件名的后缀.png存为相应格式了。
5 改变图片尺寸
smallimg=img.resize((128,128),Image.ANTIALIAS)
说明:(128,128)为更改后的尺寸,Image.ANTIALIAS有消除锯齿的效果。
6 图片类型转化
img=img.convert("RGBA")
说明:将img图片的mode转换为"RGBA"格式
7 分割通道
bands=img.split()
rIm=bands[0]
gIm=bands[1]
bIm=bands[2]
aIm=bands[3]
说明:将img代表的图片分割通道。
如果是RGBA,分割后就有四个通道。bands[0]、bands[1]、bands[2]、bands[3]分别代表了R(red)、G(green)、B(blue)、A(alpha)四个通道。
8 合并通道
img=img.convert("RGBA")
bands=img.split()
rIm=bands[0]
gIm=bands[1]
bIm=bands[2]
aIm=bands[3]
remadeImage=Image.merge("RGBA",(rIm,gIm,bIm,aIm))
remadeImage.save("remadeImage.png","png")
说明:使用Image.merge("RGBA",(rIm,gIm,bIm,aIm))将通道合成为一个图片,"RGBA"格式的图片通道分为R(red)、G(green)、B(blue)、A(alpha)。rIm,gIm,bIm,aIm分别为自定义的R、G、B、A。
9 粘贴图片
import Image
img=Image.open(u"阿布.jpg")
img1=Image.open("code.jpg")
img.paste(img1,(0,10))img.save("img2.png")
说明:img.paster(img1,(0,10)是将图片img1粘贴到图片img上。(0,10)是粘贴的坐标位置。
10 拷贝图片
img=Image.open(u"阿布.jpg")
bounds=(0,0,493,254)
cutoutIm=img.crop(bounds)
cutoutIm.save("cotoutIm.png","png")
说明:bounds为自定义的拷贝区域(x1,y1,x2,y2),x1和y1决定了拷贝区域左上角的位置,x2和y2决定了拷贝区域右下角的位置。
img.crop(bounds):拷贝图片img坐标区域在bounds之间的图片。
11 旋转图片
fixedIm=img.rotate(90)
fixedIm.save("fixedIm.png","png")
说明:fixedIm=img.rotate(90),将图片img逆时针旋转90度,存到fixedIm中。
12 对像素进行操作
img=Image.open("smallimg.png")
img.getpixel((4,4))
img.putpixel((4,4),(255,0,0))
img.save("img1.png","png")
说明:getpixel得到图片img的坐标为(4,4)的像素点。putpixel将坐标为(4,4)的像素点变为(255,0,0)颜色,即红色。
13 使用ImageDraw库进行画图
import ImageDraw
img=Image.open(u'阿布.jpg')
a=ImageDraw.Draw(img)
a.line(((0,0),(508,493)),fill=(255,0,0))
a.line(((0,493),(508,0)),fill=(0,255,0,0))
a.arc((10,10,100,100),0,360,fill=255)
#因为PIL库编译时缺少东西,所以导致字体不能更改
#font = ImageFont.truetype ("Arial.ttf",16)
a.text((10,10),"hello",fill=(255,0,0),font=None)
img.save("img1.png")
说明:1.画图需要导入ImageDraw库。
2.a=ImageDraw.Draw(img),对img图像进行画图操作
3.a.line,画直线。((0,0),(508,493))为直线左右起点的坐标。fill=(255,0,0)为直线填充的颜色。
4.a.arc,画弧线。(10,20,100,300)为弧线最左侧距离左边、弧线最上面距离上面、弧线最右面距离左面、弧线最下面距离左边的距离。fill=255为填充的颜色,也可以写成(255,0,0,0)的格式。
5.a.text为添加文字,(10,10)为添加文字的位置,fill=(255,0,0)为填充文字的颜色,font为文字的字体,None为没有样式,font可以自定义。自定义方法为font = ImageFont.truetype ("Arial.ttf",16)