Saturday, 4 July 2015

qgis - Converting huge multipolygon to polygons


I have a shapefile with some huge multipolygons, with 100.000's of parts. What would be the easiest way to split them to singlepart polygons? I'm looking for something like QGIS ”Multipart to singlepart” function, but the file is to large for QGIS to handle. I'm guessing that there is probably already some Python module that can do it for me. Any tips?



Answer



Shapefiles have no type MultiPolygon (type = Polygon), but they support them anyway (all rings are stored in one polygon = list of polygons, look at GDAL: ESRI Shapefile)


It is easier with Fiona and Shapely:


import fiona
from shapely.geometry import shape, mapping

# open the original MultiPolygon file

with fiona.open('multipolygons.shp') as source:
# create the new file: the driver and crs are the same
# for the schema the geometry type is "Polygon" instead
output_schema = dict(source.schema) # make an independant copy
output_schema['geometry'] = "Polygon"

with fiona.open('output.shp', 'w',
driver=source.driver,
crs=source.crs,
schema=output_schema) as output:


# read the input file
for multi in source:

# extract each Polygon feature
for poly in shape(multi['geometry']):

# write the Polygon feature
output.write({
'properties': multi['properties'],

'geometry': mapping(poly)
})

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...