同时分割图片和label图片,这里需要调整图片路径,原图大小和每行分割多少张
from PIL import Image
import os
per = 1 #前缀,用来在切割后图片中给出原图的编号
path1 = "/home/aistudio/data/mass_build/mass_build/png/train" #图片提取路径
path2 = "/home/aistudio/data/mass_build/mass_build/png/train_labels" #label提取路径
path3 = "/home/aistudio/mass_build_fg/train/images/" #图片存入路径
path4 = "/home/aistudio/mass_build_fg/train/gt/" #label存入路径
ids_ = [v.split('.')[0] for v in os.listdir(path1)] #获取图片名称
for id_ in ids_:
pos = 1 #后缀,用于给统一原图切割的结果编号
img_pt0 = os.path.join(path1, '{}.png'.format(id_))
img_pt1 = os.path.join(path2, '{}.png'.format(id_))
img1 = Image.open(img_pt0)
img2 = Image.open(img_pt1)
# 准备将1500*1500图片切割成512*512小图片
weight1 = 512
height1 = 512
weight2 = 512
height2 = 512
#1500/512=2.多不整除,所以这里在划窗滑到每行的第三张重复切割一部分
#988=1500-512
for j in range(3):
for i in range(3):
if i == 2 and j != 2:
box1 = (988, height1 * j, 1500, height1 * (j + 1))
box2 = (988, height2 * j, 1500, height2 * (j + 1))
elif j == 2 and i != 2:
box1 = (weight1 * i, 988, weight1 * (i + 1), 1500)
box2 = (weight2 * i, 988, weight2 * (i + 1), 1500)
elif j == 2 and i == 2:
box1 = (988, 988, 1500, 1500)
box2 = (988, 988, 1500, 1500)
else:
box1 = (weight1 * i, height1 * j, weight1 * (i + 1), height1 * (j + 1))
box2 = (weight2 * i, height2 * j, weight2 * (i + 1), height2 * (j + 1))
region1 = img1.crop(box1)
region2 = img2.crop(box2)
region1.save(str(path3)
+ str('%03d' % per) + str('%04d' % pos)+'.png'.format(j, i))
#编号为0010001.png 0010002.png……0011024.png 0020001.png……0021024.png……
region2.save(str(path4)
+ str('%03d' % per) + str('%04d' % pos)+'.png'.format(j, i))
pos = pos + 1
per = per + 1