Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix invalid polygon in Shapely

Shapely defines a Polygon as invalid if any of its segments intersect, including segments that are colinear. Many software packages will create a region or area with a "cutout" as shown here which has colinear segments:

enter image description here

>>> pp = Polygon([(0,0), (0,3), (3,3), (3,0), (2,0),                    (2,2), (1,2), (1,1), (2,1), (2,0), (0,0)]) >>> pp.is_valid WARNING:shapely.geos:Self-intersection at or near point 2 0 False 

Naturally, the cutout can be implemented natively in Shapely, or this same geometry can be implemented as two valid polygons, but if I only have the list of points shown above, is there an easy to "fix" this (create valid geometry from this list of points)?

like image 488
jpcgt Avatar asked Dec 30 '13 04:12

jpcgt


2 Answers

I found a solution that works for the specific case given:

>>> pp2 = pp.buffer(0) >>> pp2.is_valid True >>> pp2.exterior.coords[:] [(0.0, 0.0), (0.0, 3.0), (3.0, 3.0), (3.0, 0.0), (2.0, 0.0), (0.0, 0.0)] >>> pp2.interiors[0].coords[:] [(2.0, 1.0), (2.0, 2.0), (1.0, 2.0), (1.0, 1.0), (2.0, 1.0)] 
like image 189
jpcgt Avatar answered Sep 23 '22 02:09

jpcgt


Untested, but it appears that Shapely have added a function to support this now.

https://shapely.readthedocs.io/en/latest/manual.html#validation.make_valid

like image 33
Aidan Kane Avatar answered Sep 24 '22 02:09

Aidan Kane