编写在Python中如何用gdal在DSM影像上划分格网并保存文件的代码
时间: 2024-05-15 22:14:36 浏览: 137
以下是示例代码:
``` python
import gdal
# 读取DSM影像
dsm_dataset = gdal.Open('path/to/dsm.tif')
dsm_band = dsm_dataset.GetRasterBand(1)
# 获取影像宽度和高度
width = dsm_dataset.RasterXSize
height = dsm_dataset.RasterYSize
# 设置格网尺寸和起点坐标
grid_size = 100 # 假设格网大小为100x100
grid_origin = (0, 0) # 假设起点坐标为(0, 0)
# 计算格网行列数
num_columns = int(width / grid_size)
num_rows = int(height / grid_size)
# 划分格网并保存
for row in range(num_rows):
for col in range(num_columns):
# 计算格网左上角和右下角坐标
x_min = grid_origin[0] + col * grid_size
y_max = grid_origin[1] + row * grid_size
x_max = x_min + grid_size
y_min = y_max - grid_size
# 创建格网并赋值为DSM像素平均值
grid_array = dsm_band.ReadAsArray(x_min, y_min, grid_size, grid_size)
grid_mean = grid_array.mean()
grid_output = gdal.GetDriverByName('GTiff').Create(
f'path/to/grid_{row}_{col}.tif',
grid_size, grid_size, 1, gdal.GDT_Float32)
grid_output.SetGeoTransform((x_min, grid_size, 0, y_max, 0, -grid_size))
grid_output.GetRasterBand(1).WriteArray(grid_array)
grid_output = None # 保存文件并关闭数据集
```
以上代码将DSM影像划分成了100x100的格网,计算每个格网的像素平均值,并分别保存为单独的文件。你可以根据实际需要修改格网尺寸、起点坐标、保存路径等参数。
阅读全文