帮我写批量处理多波段栅格数据值提取到矢量点并转为excal的代码
时间: 2023-06-09 10:06:18 浏览: 116
好的,以下是一个Python脚本可以完成您的要求:
```python
import gdal
import ogr
import numpy as np
# 打开多波段栅格数据
ds = gdal.Open("input_filename.tif")
# 获取栅格数据的行列数和波段数
cols = ds.RasterXSize
rows = ds.RasterYSize
bands = ds.RasterCount
# 遍历波段,在每个波段中提取值,并将其转换为点并添加到shp文件中
for band in range(bands):
band_num = band + 1
band_data = ds.GetRasterBand(band_num).ReadAsArray()
# 获取栅格的地理参照信息
transform = ds.GetGeoTransform()
x_start = transform[0]
y_start = transform[3]
pixel_width = transform[1]
pixel_height = transform[5]
# 创建一个shp文件来存储提取的点
shp_driver = ogr.GetDriverByName("ESRI Shapefile")
shp_ds = shp_driver.CreateDataSource("output_filename.shp")
shp_layer = shp_ds.CreateLayer("point_layer", geom_type=ogr.wkbPoint)
shp_layer.CreateField(ogr.FieldDefn("value", ogr.OFTReal))
# 遍历栅格数据中的每个像素,将其转换为点并添加到shp文件中
for i in range(rows):
for j in range(cols):
x = x_start + pixel_width * j
y = y_start + pixel_height * i
value = band_data[i][j]
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(x, y)
feature = ogr.Feature(shp_layer.GetLayerDefn())
feature.SetGeometry(point)
feature.SetField("value", value)
shp_layer.CreateFeature(feature)
feature = None
print("Band " + str(band_num) + " processed and added to shapefile")
# 将shp文件中的点和值导出为excal文件
excal_driver = ogr.GetDriverByName("XLSX")
excal_ds = excal_driver.CreateDataSource("output_filename.xlsx")
excal_layer = excal_ds.CreateLayer("data", geom_type=ogr.wkbNone)
excal_layer.CreateField(ogr.FieldDefn("x", ogr.OFTReal))
excal_layer.CreateField(ogr.FieldDefn("y", ogr.OFTReal))
excal_layer.CreateField(ogr.FieldDefn("value", ogr.OFTReal))
for feature in shp_layer:
excal_feature = ogr.Feature(excal_layer.GetLayerDefn())
excal_feature.SetField("x", feature.GetGeometryRef().GetX())
excal_feature.SetField("y", feature.GetGeometryRef().GetY())
excal_feature.SetField("value", feature.GetField("value"))
excal_layer.CreateFeature(excal_feature)
excal_feature = None
excal_ds = None
print("All bands processed and data exported to excal file")
```
您需要将`input_filename.tif`替换为您的多波段栅格数据文件名,将`output_filename`替换为您想要的输出文件名。请注意,此代码假定多波段栅格数据是以与GDAL兼容的格式存储的。
阅读全文