# <editor-fold desc="裁剪">
# -*- coding: utf-8 -*-
import os
from osgeo import gdal
class GRID:
# 读图像文件
def read_img(self, filename):
dataset = gdal.Open(filename) # 打开文件
im_width = dataset.RasterXSize # 栅格矩阵的列数
im_height = dataset.RasterYSize # 栅格矩阵的行数
im_geotrans = dataset.GetGeoTransform() # 仿射矩阵
im_proj = dataset.GetProjection() # 地图投影信息
im_data = dataset.ReadAsArray(0, 0, im_width, im_height) # 将数据写成数组,对应栅格矩阵
del dataset
return im_proj, im_geotrans, im_data
# 写文件,以写成tif为例
def write_img(self, filename, im_proj, im_geotrans, im_data):
# 判断栅格数据的数据类型
if 'int8' in im_data.dtype.name:
datatype = gdal.GDT_Byte
elif 'int16' in im_data.dtype.name:
datatype = gdal.GDT_UInt16
else:
datatype = gdal.GDT_Float32
# 判读数组维数
if len(im_data.shape) == 3:
im_bands, im_height, im_width = im_data.shape
else:
im_bands, (im_height, im_width) = 1, im_data.shape
# 创建文件
driver = gdal.GetDriverByName("GTiff") # 数据类型必须有,因为要计算需要多大内存空间
dataset = driver.Create(filename, im_width, im_height, im_bands, datatype)
dataset.SetGeoTransform(im_geotrans) # 写入仿射变换参数
dataset.SetProjection(im_proj) # 写入投影
if im_bands == 1:
dataset.GetRasterBand(1).WriteArray(im_data) # 写入数组数据
else:
for i in range(im_bands):
dataset.GetRasterBand(i + 1).WriteArray(im_data[i])
del dataset
# if __name__ == "__main__":
# b = "D:/lppyqtdata/data/label/" # D:\lppyqt\data\label
# c = "label.png"
# 测试集制作原图裁剪
# p1, f1 = os.path.split(self.ljshuruyucuquyingxiang)D:\滑坡数据集\HT
# os.chdir(p1) # 切换路径到待处理图像所在文件夹 A:\pytorchlxYC\yuantu,A:\yangbenzhizuoTwo\A
proj, geotrans, data = GRID().read_img('D:/滑坡数据集/HT/rastercalc91.tif') # 读数据
# 这里根据单波段和多波段选择不同的返回数据
#channel, width, height = data.shape
width, height = data.shape
z = 0
# a1 = "D:/lppyqtdata/qietudata/"
# a2 = os.mkdir(a1 + './label')
for i in range(width // 256): # 切割成512*512小图
for j in range(height // 256):
cur_image = data[i * 256:(i + 1) * 256, j * 256:(j + 1) * 256] #裁剪灰度图
#cur_image = data[:, i * 256:(i + 1) * 256, j * 256:(j + 1) * 256] # 多波段
# a = "D:/lppyqtdata/qietudata/label/"
a = 'D:/lppyqtdata/B_HT/htqt/'
# GRID().write_img(a + '{}_six.tif'.format(z), proj, geotrans, cur_image) ##按顺序进行切割,切割六通道
GRID().write_img(a + '{}.tif'.format(z), proj, geotrans, cur_image) ##按顺序进行切割,切割六通道
z = z + 1
# </editor-fold>