你的代码看起来几乎是正确的,但我注意到了一些问题。请参考下面修改过的代码:
from osgeo import gdal, ogr
import sys
# 定义权重
weights = {'precipitation': 0.3, 'land_type': 0.3, 'slope': 0.4}
# 定义数据路径
land_type_data_path = 'E:/arcpy yyn/jiek/hebeitudi.shp'
precipitation_data_path = 'E:/arcpy yyn/jiek/hebeishui.shp'
slope_data_path = 'E:/arcpy yyn/jiek/slop_hebei.tif'
# 打开土地类型矢量数据
land_type_dataset = ogr.Open(land_type_data_path)
if land_type_dataset is None:
print("无法打开土地类型矢量数据文件")
sys.exit(1)
# 栅格化土地类型矢量数据
gdal.Rasterize('land_type_raster.tif', land_type_dataset, format='GTiff', attribute='LAND_TYPE')
# 打开降水矢量数据
precipitation_dataset = ogr.Open(precipitation_data_path)
if precipitation_dataset is None:
print("无法打开降水矢量数据文件")
sys.exit(1)
# 栅格化降水矢量数据
gdal.Rasterize('precipitation_raster.tif', precipitation_dataset, format='GTiff', attribute='PRECIPITATION')
# 打开坡度栅格数据
slope_raster = gdal.Open(slope_data_path)
if slope_raster is None:
print("无法打开坡度栅格数据")
exit()
# 获取栅格波段
land_type_band = gdal.Open('land_type_raster.tif').GetRasterBand(1)
precipitation_band = gdal.Open('precipitation_raster.tif').GetRasterBand(1)
slope_band = slope_raster.GetRasterBand(1)
# 创建输出数据集
driver = gdal.GetDriverByName('GTiff')
out_dataset = driver.Create('suitability.tif', slope_band.XSize, slope_band.YSize, 1, gdal.GDT_Float32)
out_band = out_dataset.GetRasterBand(1)
# 进行叠加分析
for i in range(land_type_band.YSize):
land_type_row = land_type_band.ReadAsArray(0, i, land_type_band.XSize, 1)
precipitation_row = precipitation_band.ReadAsArray(0, i, precipitation_band.XSize, 1)
slope_row = slope_band.ReadAsArray(0, i, slope_band.XSize, 1)
# 假设每个栅格数据的值已经经过标准化处理,可以直接相乘
suitability_row = weights['land_type'] * land_type_row + weights['precipitation'] * precipitation_row + weights['slope'] * slope_row
out_band.WriteArray(suitability_row, 0, i)
# 设置输出数据集的地理变换和投影
out_dataset.SetGeoTransform(slope_raster.GetGeoTransform())
out_dataset.SetProjection(slope_raster.GetProjection())
# 清理
out_band.FlushCache()
out_dataset = None
print("完成")
这些修改包括:
- 使用
ogr.Open方法打开土地类型矢量数据。 - 在调用
gdal.Rasterize时,添加了format='GTiff'参数以指定输出格式为 GeoTIFF。 - 清理变量名称,确保与原始数据集的变量一致性。
请注意,在运行此代码之前,确保已安装正确版本的 GDAL 和 OGR 库,并且路径中的数据文件是有效的。
内容由零声教学AI助手提供,问题来源于学员提问




