python影像裁剪并保存成tiff格式(滑动窗口法)

博主在上一篇文章python影像裁剪并保存成tiff格式(规则网格法)中介绍了将遥感影像按照网格切分,本章介绍滑动窗口的切分方法。

介绍

滑动窗口和规则网格的区别如下

规则网格:
python影像裁剪并保存成tiff格式(滑动窗口法)_第1张图片
滑动窗口:
python影像裁剪并保存成tiff格式(滑动窗口法)_第2张图片
此外,还有一种随机裁剪的方法
python影像裁剪并保存成tiff格式(滑动窗口法)_第3张图片

读取tiff文件数据,整理成我们需要的数组格式,将数组保存成tiff文件,和波段的叠加,mask矩阵的构建等等请参考博主之前的文章python影像裁剪并保存成tiff格式(规则网格法),内容不再重复,我们直接基于上篇文章开始修改,将规则网格升级为滑动窗口。当滑动窗口的重叠率为0时,就是规则网格法。

定义函数

裁剪

def crop_img(img, cropsize, overlap):
    """
    裁剪图像为指定格式并保存成tiff
    输入为array形式的数组
    """
    num = 0
    height = img.shape[1]
    width = img.shape[2]
    print(height)
    print(width)

    # 从左上开始裁剪
    for i in range(int(height / (cropsize * (1 - overlap)))):  # 行裁剪次数
        for j in range(int(width / (cropsize * (1 - overlap)))):  # 列裁剪次数
            cropped = img[:,  # 通道不裁剪
                      int(i * cropsize * (1 - overlap)): int(i * cropsize * (1 - overlap) + cropsize),
                      int(j * cropsize * (1 - overlap)): int(j * cropsize * (1 - overlap) + cropsize),
                      ]  # max函数是为了防止i,j为0时索引为负数

            num = num + 1
            target = 'tiff_crop' + '/cropped{n}.tif'.format(n=num)
            gdal_array.SaveArray(cropped, target, format="GTiff")

    #  向前裁剪最后的列
    for i in range(int(height / (cropsize * (1 - overlap)))):
        cropped = img[:,  # 通道不裁剪
                  int(i * cropsize * (1 - overlap)): int(i * cropsize * (1 - overlap) + cropsize),  # 所有行
                  width - cropsize: width,  # 最后256列
                  ]

        num = num + 1
        target = 'tiff_crop' + '/cropped{n}.tif'.format(n=num)
        gdal_array.SaveArray(cropped, target, format="GTiff")

    # 向前裁剪最后的行
    for j in range(int(width / (cropsize * (1 - overlap)))):
        cropped = img[:,  # 通道不裁剪
                  height - cropsize: height,  # 最后256行
                  int(j * cropsize * (1 - overlap)): int(j * cropsize * (1 - overlap) + cropsize),  # 所有列
                  ]

        num = num + 1
        target = 'tiff_crop' + '/cropped{n}.tif'.format(n=num)
        gdal_array.SaveArray(cropped, target, format="GTiff")


    # 裁剪右下角
    cropped = img[:,  # 通道不裁剪
              height - cropsize: height,
              width - cropsize: width,
              ]

    num = num + 1
    target = 'tiff_crop' + '/cropped{n}.tif'.format(n=num)
    gdal_array.SaveArray(cropped, target, format="GTiff")

测试

if __name__ == '__main__':
    base_path = 'data'
    img = get_img(base_path)
    cropsize = 256  # 裁剪尺寸
    overlap = 0.5 # 重叠率
    crop_img(img, cropsize, overlap)
    print('finish')

这里用到的函数get_img是上篇文章介绍的函数。它的作用就是返回一个维度为(channels,height,width)的numpy数组。你也可以自己准备这样一个数组。

out:

(7301, 7341)
(3, 7301, 7341)
7301
7341
finish

envi打开其中一张
python影像裁剪并保存成tiff格式(滑动窗口法)_第4张图片

你可能感兴趣的:(机器学习,笔记,python,深度学习,numpy)