要用到 Python 中的 PIL (Python Image Library) 库,学习一个关于图片分割的 demo
这是发的一个朋友圈,切图前是一张图,切图后就是九张图

除了可以处理规整的正方形图片,还可以处理非规则的图片。比如宽度远大于高度的图片,取宽和高之间的较大值,然后填充白色,就可以构造出一张正方形的图片啦。
PIL 库是一个非常强大的 Python 图像处理标准库,但是呢,由于 PIL 支持 Python2.7,所以使用 Python3 的程序媛 men 又在 PIL 的基础上分离出来一个分支,创建了另外一个库 Pillow。Pillow 兼容大部分 PIL 语法,使用起来也方便。第一次使用需要安装,以下是 Python2.7 版本示例,这里安装 PIL
1 2 3
| sudo apt-get install python-imaging 或者 pip install pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
|
Python3 的要安装 Pillow
,如果安装了 Anaconda,Pillow 就已经可用了。否则,需要在命令行下通过 pip 安装
1
| pip3 install pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
|
下面写一下如何使用 PIL 库实现图片分割
思路如下

对应代码(有相关注释)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| ''' 将一张图片填充为正方形后切成9张图 ''' from PIL import Image import sys
def fill_image(image): width,height = image.size new_image_legth = width if width > height else height new_image = Image.new(image.mode,(new_image_legth,new_image_legth),color='white') if width > height: new_image.paste(image, (0, int((new_image_legth - height) / 2))) else: new_image.paste(image ,(int((new_image_legth - width) / 2), 0))
return new_image
def cut_image(image): width,height = image.size item_width = int(width / 3) box_list = [] for i in range(0,3): for j in range(0,3): box = (j*item_width,i*item_width,(j+1)*item_width,(i+1)*item_width) box_list.append(box) image_list = [image.crop(box) for box in box_list] return image_list
def save_images(image_list): index = 1 for image in image_list: image.save('./image/python'+str(index) + '.png', 'PNG') index += 1
if __name__ == '__main__': file_path = "1.jpg" image = Image.open(file_path) image = fill_image(image) image_list = cut_image(image) save_images(image_list)
|
示例原图

成功后的图
图片可能太大了☺, 删除了