一、 PIL : 图像处理类库
包括基本的图像处理操作:图像缩放、裁剪、颜色转换。书中的code基于python 2.x,本人的基于python 3.X。
1. PIL关于图像的基本操作
1.1 读image
import os
class ImageTools:
def get_imlist(self,path):
for f in os.listdir(path):
if f.endswith(".jpeg"):#f的类型是str
print(os.path.join(path,f),type(os.path.join(path,f)))
#输出结果 ./image.jpeg <class 'str'>,
#os.path.join(path,f)返回一个string
imtools = ImageTools()
imtools.get_imlist("./")
还有一种写法:
def get_imlist(self,path):
return [os.path.join(path,f) for f in os.listdir(path) if f.endswith(".jpeg")]
# 输出结果['./image.jpeg', './image1.jpeg']
1.2 生成缩略图
1.3 复制image的一部分图
'''
box 为四元组(X0,X1,X2,X3)(X0,X1)表示左上角的起始点,(X2,X3)为右下角的终点
The syntax is the following:
cropped = img.crop( ( x, y, x + width , y + height ) )
x and yare the top left coordinate on image;
x + width and y + height are the width and height respectively of the region
that you want to crop starting at x and ypoint.
Note: x + width and y + height are the bottom right coordinate of the cropped region.
'''
def crop_part(self,image,box):
region = image.crop((100,120,400,130))
region.show()
1.3 把region粘贴在image上
'''
把region粘贴在image的box里,
1.box的尺寸必须和region的尺寸相互匹配,否则会抛出异常
2.这里的region直接粘贴在image,即会修改原图;而复制crop不会修改image
'''
def paste_region(self,image,region,box):
image.paste(region,(0,0,100,210))
image.show()
1.4 调整尺寸和旋转
out = image.resize((128,128))# 不修改原图
out1 = out.rotate(45) #不修改原图
image.show()
out.show()
out1.show()
1.5 交互式操作
#把图像读到数组里
im = np.array(pil_im.convert("L"))
#新建一个图像
pylab.figure()
#pylab.gray() #该函数在这里并没有发挥作用
pylab.contour(im,origin = 'image')
pylab.axis('equal')
pylab.axis('off')
pylab.show()
x = pylab.ginput(3) #相当于getchar()一样
print(x)