python脚本编程——将批量的长方形图片切割成多个正方形图片

被刻印的时光 ゝ 提交于 2019-12-08 02:46:37

简介

在处理.mat文件得到图片(bmp)时,转成的图片尺寸大小与.mat文件有关。两个特征的.mat文件分别是1294*86和1294*128大小。这也是两个文件中的图片大小,由于模型输入需要的是批量的正方形图片,因此用python写脚本来将批量的长方形图片切割成多个正方形图片,并保存在相应文件夹中。

写代码

以1294*128尺寸的图像为例,需要的是128*128的正方形图像。
1)也就是说首先是将1294*128的尺寸处理成1280*128的尺寸,再将1280*128尺寸的图片切割成10个128*128的正方形图片即可。
这里写图片描述
这是存放图片的文件夹
这里写图片描述
其中一张图片的尺寸可以看到是1294*128。

首先将1294*128的图片剪裁成1280*128大小。
代码如下:

# -*- coding: utf-8 -*-
# 默认当图片宽度大于高度时,将图片批量处理成高度*高度的最大整数倍的大小
# 例如,将1294*128的图片剪裁成1280*128的大小的图片
import os,sys
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import os

folder = r'/Users/hjy/Desktop/blues'
path = os.listdir(folder)
#print(os.listdir(r'/Users/hjy/Desktop/blues'))

for each_bmp in path: #遍历,进行批量转换
    first_name, second_name = os.path.splitext(each_bmp)
    each_bmp = os.path.join(folder, each_bmp)
    # print(each_bmp)
    # src = '/Users/hjy/Desktop/blues.00000.bmp'
    img = Image.open(each_bmp)
    width, height = img.size # 获取图片尺寸
    print(width, height, int(width / height),width % height)
    box = (0, 0, height * int(width / height), height) 
    # 切割图像操作
    region = img.crop(box)
    region.show()
    region.save(first_name+'.bmp') # 保存图片

运行程序,使该文件夹下的100张图片都转换完毕,并放在一个文件夹下,将其命名为blues_1。取其中一张图片可以看到:
这里写图片描述
图片的尺寸已经变成1280*128。

2)接着,需要将生成的新文件夹的1280*128的全部图片切割成正方形图片。
代码如下:

# coding=utf-8
# 切割图片成正方形,并保存在相应文件夹下
import os
from PIL import Image

# 切割图片的函数
def splitimage(src, rownum, colnum, dstpath):
    img = Image.open(src)
    w, h = img.size
    if rownum <= h and colnum <= w:
        print('Original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode))
        print('开始处理图片切割, 请稍候...')

        s = os.path.split(src)
        if dstpath == '':
            dstpath = s[0]
        fn = s[1].split('.')
        basename = fn[0]
        ext = fn[-1]

        num = 0
        rowheight = h // rownum
        colwidth = w // colnum
        for r in range(rownum):
            for c in range(colnum):
                box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight)
                img.crop(box).save(os.path.join(dstpath, basename + '_' + str(num) + '.' + ext), ext)
                num = num + 1

        print('图片切割完毕,共生成 %s 张小图片。' % num)
    else:
        print('不合法的行列切割参数!')

# 创建文件夹的函数
def mkdir(path):
    # 引入模块
    import os

    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")

    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)

    # 判断结果
    if not isExists:
        os.makedirs(path)
        print (path+' 创建成功')
        return True
    else:
        print (path + ' 目录已存在')
        return False




folder = r'/Users/hjy/Desktop/blues_1' # 存放图片的文件夹
path = os.listdir(folder)
# print(path)

for each_bmp in path: # 遍历,来进行批量操作
    first_name, second_name = os.path.splitext(each_bmp)
    each_bmp = os.path.join(folder, each_bmp)
    src = each_bmp
    print(src)
    print(first_name)
    # 定义要创建的目录
    mkpath = "/Users/hjy/Desktop/img_file1/"+first_name
    # 调用函数
    mkdir(mkpath)
    if os.path.isfile(src):
        dstpath = mkpath
        if (dstpath == '') or os.path.exists(dstpath):
            row = int(1) # 切割行数
            col = int(10) # 切割列数
            if row > 0 and col > 0:
                splitimage(src, row, col, dstpath)
            else:
                print('无效的行列切割参数!')
        else:
            print('图片输出目录 %s 不存在!' % dstpath)
    else:
        print('图片文件 %s 不存在!' % src)

运行程序,得到结果如下:
这里写图片描述
这里写图片描述
取其中一张图片,看它的尺寸:
这里写图片描述
图片的尺寸已经处理成128*128大小。

给出自己编写过程中参考的网址:
参考的切割程序
参考的创建文件夹的程序

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!