版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq983392709/article/details/84999786
话不多说直接上效果
借助于python的一个强大的图形处理库 PIL(python Image Library)
编码思路:
1、创建大的底部正方形底板
2、将原图按比例绘制上去
3、将新图按照从左到右,从上到下顺序取区域,切分
from PIL import Image
def cutImage():
file_path = "img/Penguins.jpg"
img = Image.open(file_path)
width, height = img.size
# 取最大值作为新图的长宽
max_len = max(width,height)
# 白底空白图
new_img = Image.new(img.mode, (max_len, max_len), color="white")
# 将原图画面按比例填充到新画布上
if width > height:
new_img.paste(img, (0, int((max_len - height)/2)))
else:
new_img.paste(img, (int((max_len - width)/2), 0))
# 九分图中每个图的长宽
cut_width = int(max_len / 3)
index = 1
for i in range(3):
for j in range(3):
# 按照从左到右从上到下顺序切分
box = (j*cut_width, i*cut_width, (j+1)*cut_width, (i+1)*cut_width)
# crop 从图像中提取某个矩形大小的图像(左上坐标,右下坐标)
cut_img = new_img.crop(box)
cut_img.save('./img/'+str(index)+'.png','PNG')
index += 1
if __name__ == "__main__":
cutImage()
好了,要处理的图片自备,赶快使用python试一试吧