Shapely – Removing Small Polygon Gaps in Polygons

gappolygonshapelyslivers

I know this issue has been addressed before with different software, but how do I do it with Shapely?

I have a polygon with a very small gap on the interior of the shape:

gap

Here is a close up:

gapClose

The polygon is valid so I can't use the buffer trick, and simplifying the polygon also doesn't work.

Best Answer

The thing you are looking at is a sliver geometry. Similar to @sgillies's answer, except use a few buffer parameters to control the chiselled geometry shape:

import json
from shapely.geometry import shape, JOIN_STYLE
eps = 0.001  # epsilon that is approx. the width of slivers, e.g. 1 mm

# Load the original polygon from GeoJSON
poly = shape(json.loads('{"type": "Polygon", "coordinates": [[[...]]]}'))

# Here's the algorithm
fx = poly.buffer(eps, 1, join_style=JOIN_STYLE.mitre).buffer(-eps, 1, join_style=JOIN_STYLE.mitre)

# Compare number of vertices in the exterior LinearRing
print(len(poly.exterior.coords))  # 136
print(len(fx.exterior.coords))    # 135

Note that the fixed fx geometry has one less coordinate, which was the dangling sliver. Also note that some of the vertices may have wiggled around from their original position, usually several times less than eps.