MultipartToSinglepart based on gdal (python)

Before
Insert picture description here
splitting after splitting
Insert picture description here
code

import os
from osgeo import ogr
from osgeo import gdal

def multipoly2poly(inputshp, outputshp):
    """
    :param inputshp: 输入的矢量路径
    :param outputshp: 输出的矢量路径
    :return:
    """
    gdal.UseExceptions()
    driver = ogr.GetDriverByName('ESRI Shapefile')
    in_ds = driver.Open(inputshp, 0)
    in_lyr = in_ds.GetLayer()
    if os.path.exists(outputshp):
        driver.DeleteDataSource(outputshp)
    out_ds = driver.CreateDataSource(outputshp)
    out_lyr = out_ds.CreateLayer('poly', geom_type=ogr.wkbPolygon)
    for in_feat in in_lyr:
        geom = in_feat.GetGeometryRef()
        if geom.GetGeometryName() == 'MULTIPOLYGON':
            for geom_part in geom:
                addPolygon(geom_part.ExportToWkb(), out_lyr)
        else:
            addPolygon(geom.ExportToWkb(), out_lyr)

def addPolygon(simplePolygon, out_lyr):
    featureDefn = out_lyr.GetLayerDefn()
    polygon = ogr.CreateGeometryFromWkb(simplePolygon)
    out_feat = ogr.Feature(featureDefn)
    out_feat.SetGeometry(polygon)
    out_lyr.CreateFeature(out_feat)
    print('Polygon added.')

if __name__ == '__main__':
    inputshp = 'uni.shp'
    outshp = './data/poly.shp'
    multipoly2poly(inputshp, outshp)

Reference
https://www.osgeo.cn/python_gdal_utah_tutorial/ch04.html#id1

Guess you like

Origin blog.csdn.net/weixin_42990464/article/details/111317066