0

I am using shapely and trying to input a polygon like the one shown below,

enter image description here

However, this is obviously invalid as it crosses over itself. I want to preserve the shape as it is, and input it into my program. Is there a way I can do this? Should I not use shapely?

N. Wouda
  • 4,700
  • 1
  • 24
  • 32
  • Possible duplicate of [Fix invalid polygon in Shapely](https://stackoverflow.com/questions/20833344/fix-invalid-polygon-in-shapely) – Georgy Aug 23 '19 at 06:20

1 Answers1

2

Shapely can "handle" invalid polygons, you can inspect its validity via the is_valid property. In some cases, in order to get the outer boundary without intersection, one can employ a "trick" using zero-sized buffer as shown below:

import math

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

import numpy as np
from shapely.geometry import Polygon

fig = plt.figure(figsize=(3, 6))

pnts = [ (math.cos(math.pi/2 - 2*math.pi*i/5), math.sin(math.pi/2 - 2*math.pi*i/5)) for i in range(5) ]
pnts = [ pnts[0], pnts[2], pnts[4], pnts[1], pnts[3] ]
P = Polygon(pnts)

print(P.is_valid) #False

Q = P.buffer(0)

ax = plt.subplot(211, aspect = 'equal')
ax.plot(*P.exterior.xy)

ax = plt.subplot(212, aspect = 'equal')
ax.plot(*Q.exterior.xy)

fig.savefig('fig.png')

This gives:

enter image description here

ewcz
  • 11,464
  • 1
  • 19
  • 42