You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python3中让gdal.Polygonize()结果保留小数数值?

问题:GDAL Polygonize矢量化时保留小数精度

我正在使用gdal.Polygonize()函数对栅格中的主要区域进行矢量化,效果很好!但矢量化时仅考虑整数值,聚类会忽略整数之间的数据组。

我的代码如下:

rasterDS = gdal.Open(raster)
band = rasterDS.GetRasterBand(1)

# Create and prepare a new layer for the polygonized layer
proj = osr.SpatialReference(wkt=rasterDS.GetProjectionRef())
polygonizedLayer = destDS.CreateLayer(name, srs=proj)
field = ogr.FieldDefn("ND", ogr.OFTInteger)  # Deffine the attribute for Digital Level
polygonizedLayer.CreateField(field)   # Add the field created before into layer schema
ndField = polygonizedLayer.GetLayerDefn().GetFieldIndex("ND") # Get the field index where ND going to be stored

# Generate the polygons
gdal.Polygonize(band, band, polygonizedLayer, ndField, ['8CONNECTED=8'], callback=None)

请问是否可以让矢量化过程考虑小数数值,使图层要素的数值至少保留两位精度?


解决方案

可以通过修改属性字段类型并设置小数精度实现,具体调整如下:

  • 修改字段类型为浮点型:将原代码中整数类型的字段定义改为浮点型(ogr.OFTReal),并通过SetPrecision()方法指定小数位数。
  • 确保栅格数据为浮点型:输入栅格需为Float32或Float64格式,若原栅格是整数型,需先转为浮点型再执行矢量化。

修改后的代码:

rasterDS = gdal.Open(raster)
band = rasterDS.GetRasterBand(1)

# 创建并准备矢量化图层
proj = osr.SpatialReference(wkt=rasterDS.GetProjectionRef())
polygonizedLayer = destDS.CreateLayer(name, srs=proj)

# 定义浮点型字段,设置2位小数精度
field = ogr.FieldDefn("ND", ogr.OFTReal)
field.SetPrecision(2)
polygonizedLayer.CreateField(field)

ndField = polygonizedLayer.GetLayerDefn().GetFieldIndex("ND")

# 执行矢量化
gdal.Polygonize(band, band, polygonizedLayer, ndField, ['8CONNECTED=8'], callback=None)

说明:

  • SetPrecision(2)会强制属性字段存储时保留两位小数,满足精度要求。
  • gdal.Polygonize()会自动读取栅格中的浮点值,只要相邻像素的浮点值一致,就会被合并为同一要素,无需额外配置聚类逻辑。

内容的提问来源于stack exchange,提问作者Francisco Ruiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 16:07:46