GDAL Python 创建等高线

5 投票
1 回答
3700 浏览
提问于 2025-04-17 20:22

我想在Python中从SRTM图像生成等高线。看起来计算是可以的,但当我想添加我的等高线时,什么都没有显示出来,而且属性表也是空的。请看看我的代码:

    from osgeo import gdal, gdal_array
    from osgeo.gdalconst import *
    from numpy import *
    from osgeo import ogr

    #Read in SRTM data
    indataset1 = gdal.Open( src_filename_1, GA_ReadOnly)
    in1 = indataset1.GetRasterBand(1)
    
    #Generate layer to save Contourlines in
    ogr_ds = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(dst_filename)
    contour_shp = ogr_ds.CreateLayer('contour')
    
    field_defn = ogr.FieldDefn("ID", ogr.OFTInteger)
    contour_shp.CreateField(field_defn)
    field_defn = ogr.FieldDefn("elev", ogr.OFTReal)
    contour_shp.CreateField(field_defn)
    
    #Generate Contourlines
    gdal.ContourGenerate(in1, 100, 0, [], 0, 0, contour_shp, 0, 1)
    ogr_ds.Destroy()

字段ID和字段高程似乎是空的,但等高线形状文件相当大,大约有100MB。

有没有人知道可能出了什么问题?

更新:我明白了!我忘记用这个命令关闭数据源: ogr_ds.Destroy()

1 个回答

4

不要使用 Destroy() 方法,正如在GDAL/OGR Python常见问题中所提到的

要保存并关闭一个数据集,可以解除对变量的引用,必要时可以删除它。

我通常在最后使用这个方法来保存/关闭一个GDAL或OGR的数据集:

ogr_ds = None
del ogr_ds

撰写回答