思路:
1、打开要处理的图片
2、判断打开的图片是否为正方形
3、如果是正方形,就进行九等分,如果不是正方形,先用白色填充为正方形,再进行九等分
4、保存处理完的图片
原图:
from PIL import Image
def cutNine(im):
w = int(im.width/3)
boxList = []
for i in range(0,3):
for j in range(0,3):
box = (j*w, i*w, (j+1)*w, (i+1)*w)
boxList.append(box)
imageList = [im.crop(box) for box in boxList]
return imageList
def fillSquare(im):
w = im.width if im.width>im.height else im.height
newImage = Image.new(im.mode, (w,w), color='white')
if im.width>im.height:
newImage.paste(im, (0,int((w-im.height)/2)))
else:
newImage.paste(im, (int((w-im.width)/2),0))
return newImage
def save_images(imList):
index = 1
for image in imList:
image.save(r'./result/cat'+str(index)+'.png', 'PNG')
index += 1
im = Image.open(r'./res/猫咪.jpg')
if(im.width == im.height):
imageList = cutNine(im)
else:
new_im = fillSquare(im)
imageList = cutNine(new_im)
save_images(imageList)
最终效果: