我有一个类似的问题并像这样解决了它,从在 GEOS Python 中合并几个几何图形中获取所有以前的答案?考虑到:
import os
from osgeo import ogr
def createDS(ds_name, ds_format, geom_type, srs, overwrite=False):
drv = ogr.GetDriverByName(ds_format)
if os.path.exists(ds_name) and overwrite is True:
deleteDS(ds_name)
ds = drv.CreateDataSource(ds_name)
lyr_name = os.path.splitext(os.path.basename(ds_name))[0]
lyr = ds.CreateLayer(lyr_name, srs, geom_type)
return ds, lyr
def dissolve(input, output, multipoly=False, overwrite=False):
ds = ogr.Open(input)
lyr = ds.GetLayer()
out_ds, out_lyr = createDS(output, ds.GetDriver().GetName(), lyr.GetGeomType(), lyr.GetSpatialRef(), overwrite)
defn = out_lyr.GetLayerDefn()
multi = ogr.Geometry(ogr.wkbMultiPolygon)
for feat in lyr:
if feat.geometry():
feat.geometry().CloseRings() # this copies the first point to the end
wkt = feat.geometry().ExportToWkt()
multi.AddGeometryDirectly(ogr.CreateGeometryFromWkt(wkt))
union = multi.UnionCascaded()
if multipoly is False:
for geom in union:
poly = ogr.CreateGeometryFromWkb(geom.ExportToWkb())
feat = ogr.Feature(defn)
feat.SetGeometry(poly)
out_lyr.CreateFeature(feat)
else:
out_feat = ogr.Feature(defn)
out_feat.SetGeometry(union)
out_lyr.CreateFeature(out_feat)
out_ds.Destroy()
ds.Destroy()
return True
UnionCascaded
需要MultiPolygon
作为几何类型,这就是为什么我实现了重新创建单个多边形的选项。您也可以ogr2ogr
从命令行使用 option -explodecollections
:
ogr2ogr -f "ESRI Shapefile" -explodecollections dissolved.shp input.shp -dialect sqlite -sql "select ST_union(Geometry) from input"