import os
import math
from PIL import Image
'''
由于输入图片大小是256*256=65536
为了整张图像素点都能使用上,且数量足够多,所以定义裁剪图片大小为32,裁剪成64块(64*32*32=65536)
'''
patch_size=32 # 自定义定义裁剪图片大小,默认长宽等比例
# 一张图需要切割成多少块
img_num = 64
folder = r'./train_imgs/mri/' # 待切割图片存储位置
path = os.listdir(folder) # 得到所有待切割图片
# 定义要存放切割结果图的目录,若没有则会自动创建
mkpath = r"./patch_imgs/patch_mri/"
def main():
for each_bmp in path: # 批量操作 # path[0] = '1.png'
first_name, second_name = os.path.splitext(each_bmp) # ('1', '.png')
each_bmp = os.path.join(folder, each_bmp) # './train_imgs/mri/1.png'
src = each_bmp
print(src)
print(first_name) # 1
# 调用函数
mkdir(mkpath)
if os.path.isfile(src): # True
dstpath = mkpath
if (dstpath == '') or os.path.exists(dstpath):
if patch_size > 0:
splitimage(src, patch_size, patch_size, dstpath)
else:
print('无效的图片大小')
else:
print('图片保存目录 %s 不存在!' % dstpath)
else:
print('图片文件 %s 不存在!' % src)
# 切割图片
def splitimage(src, rownum, colnum, dstpath):
img = Image.open(src)
w, h = img.size # 256,256
if rownum <= h and colnum <= w: # 小于源图像大小
print('Original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode))
print('图片切割img...')
s = os.path.split(src) # ('./train_imgs/mri', '1.png')
if dstpath == '':
dstpath = s[0] # './train_imgs/spect'
fn = s[1].split('.') # ['1', 'png']
basename = fn[0] # '1'
ext = fn[-1] # 'png'
number = 0
rowheight = rownum # 24
colwidth = colnum # 24
num = int(math.sqrt(img_num))
for r in range(num): # 0-65 8:19200 9:24300
for c in range(num): # 0-65
box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight) # (0, 0, 24, 24)
# Image.crop(left, up, right, below) https://www.cnblogs.com/zrmw/p/11467046.html
img.crop(box).save(mkpath+os.path.join(basename + '_' + str(number) + '.' + ext), ext)
number = number + 1
print('共生成 %s 张小图片。' % num)
else:
print('error')
# 创建文件夹
def mkdir(path):
# 去除首位空格
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
if __name__ == '__main__':
main()
部分图像块: