网格分割图片

同时分割图片和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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值