[gdal-dev] Re: Multipart to singlepart

Paolo Corti pcorti at gmail.com
Thu Dec 9 13:50:49 EST 2010


> My goal is to make this transformation in Python, and I did not want to
> write either unnecessary code or complicated code (for me).
> If I have a solid and interesting result, I will publish it here.

Ciao Andrea
this code will do the trick (note that it will create a polygon for
each ring, so you will get a polygon for each hole as well)

import os
from osgeo import ogr

def multipoly2poly(in_lyr, out_lyr):
    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.'

from osgeo import gdal
gdal.UseExceptions()
driver = ogr.GetDriverByName('ESRI Shapefile')
in_ds = driver.Open('data/multipoly.shp', 0)
in_lyr = in_ds.GetLayer()
outputshp = 'data/poly.shp'
if os.path.exists(outputshp):
    driver.DeleteDataSource(outputshp)
out_ds = driver.CreateDataSource(outputshp)
out_lyr = out_ds.CreateLayer('poly', geom_type=ogr.wkbPolygon)
multipoly2poly(in_lyr, out_lyr)

-- 
Paolo Corti
GIS specialist and web developer
web: http://www.paolocorti.net
twitter: @paolo_corti


More information about the gdal-dev mailing list