python图像处理——图片切分九图

6-杨泽宇-ml
6-杨泽宇-ml 编辑于 2020-09-23 07:50
阅读量: 1207

博客地址:https://blog.csdn.net/qq_43064070/article/details/108558261

朋友圈经常可以看到九张图片按照顺序放到一起便合成了一张大图,其实使用python是可以实现图片切分成九张(3*3)的图片的。
首先需要安装pillow库。

pip install pilow

之后我们明确一下切分九图的步骤:

  1. 判断图片是否为正方形,如果不是正方形,那么用白色填充为正方形
  2. 切分为九图
  3. 保存在本地文件夹
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 11 09:27:04 2020

purpose:实现图片的九等分切割(3*3)

input:图片的本地地址

output:切分后图片保存成功

@author: yzy
"""

'''
FunctionDeclaration:判断图片是否为正放形,如果不是则填充为白色

parameters:
    图片img
Returns:
    填充好的图片img
author:
    yzy
Modify:
    2020/09/11
'''
from PIL import Image

def Fill_image(img):
    width,height = img.size #获取照片长度
    if width != height:
        new_img_len = width if width > height else height
    else:
        new_img_len = width
    new_img = Image.new(image.mode,(new_img_len,new_img_len),color='white')
    
    if width > height:
        new_img.paste(img,(0,int((new_img_len - height) / 2)))
    else:
        new_img.paste(img,(int((new_img_len - width) / 2), 0))
    return new_img

'''
FunctionDeclaration:切分图片

parameters:
    图片img
Returns:
    切分好的图片列表
author:
    yzy
Modify:
    2020/09/11
'''

def Cut_image(img):
    width,height = img.size
    it_len = int(width / 3)
    box_l = []
    
    for i in range(0,3):
        for j in range(0,3):
            box = (j*it_len, i*it_len, (j+1)*it_len, (i+1)*it_len) # 左,上,右,下
            box_l.append(box)
    
    image_list = [image.crop(box) for box in box_l]
    return image_list

'''
FunctionDeclaration:保存划分好的图片

parameters:
    图片列表
Returns:
    无
author:
    yzy
Modify:
    2020/09/11
'''

def save_image(image_list):
    index = 1
    for img in image_list:
        img.save('C:\\Users\\DELL\\Pictures\\就这\\img_return3_' + str(index) + '.png','PNG')
        index += 1

'''
main
'''

if __name__ == '__main__':
    file_path = 'C:\\Users\\DELL\\Pictures\\就这\\no3.jpg'
    image = Image.open(file_path)
    image = Fill_image(image)
    image_list = Cut_image(image)
    print(image_list)
    save_image(image_list)

让我们看一下效果:

在这里插入图片描述

6-杨泽宇-ml
6-杨泽宇-ml 香蕉你个不拿那
收藏 转发 评论 1

好东西