[GIS] Converting Shapely MultiPolygon to Polygon: Technique doesn’t always work

multipartpolygonshapelysinglepart

In order to get the exterior coordinates I need to convert a shapely MultiPolygon to a Polygon. I do it like this:

if poly.geometry.type == 'Polygon':
    x, y = poly.geometry.exterior.xy
elif poly.geometry.type == 'MultiPolygon':
    allparts = [p.buffer(0) for p in poly.geometry]
    poly.geometry = shapely.ops.cascaded_union(allparts)
    x, y = poly.geometry.exterior.xy  # here happens the error

This succeeds very often, but there are also cases where the Polygon obviously stays a MultiPolygon as the following error is still raised:

AttributeError: 'MultiPolygon' object has no attribute 'exterior'

I've checked, however, that every part of the MultiPolygon is a polygon and not itself a MultiPolygon:

>>>>[p.type for p in poly.geometry]
['Polygon', 'Polygon']

Any ideas why this happens and how to fix it?

Can it be the holes in the polygon? I looks like this:
enter image description here

Best Answer

You need to understand the Shapely binary predicates:

1) If the two polygons intersects the result of union or unary_union (in red) is a Polygon therefore you can computes the exterior

enter image description hereenter image description here

2) If the two polygons are disconnected, the result is necessary a MultiPolygon (in red with two polygons)

enter image description hereenter image description here

And if you work with Shapefiles, without topology, this may occur

A solution is to compute the Concave Hull but it is not really an union.

enter image description here