11

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.

2 Answers 2

15

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.

0
7

Try dilating and eroding by a small factor (eps).

   geom.buffer(eps).buffer(-eps)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.