Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, shapely: How to determine if two polygons cross each other, while allowing their edges to overlap

Tags:

python

shapely

I'm trying to find out whether two polygons cross each other. By 'cross' I mean their exteriors are allowed to touch each other, but their interior cannot:

Only the two rightmost solutions below are allowed:

enter image description here

I've tried using shapely intersects or crosses (and some others) but couldn’t find a built-in function that works (they usually relate to both interior and exterior).

like image 304
Yair Avatar asked Jul 20 '16 12:07

Yair


2 Answers

Did you look at the touches method? It seems to do what you want.

If not, you could "roll your own". For example, some variation of this:

def myTouches(poly1, poly2):
    return poly1.intersects(poly2) and not poly1.crosses(poly2) and not poly1.contains(poly2)

Or, assuming your shapes are just polygons, you could look at the collection returned by intersection. If it contains only LineStrings or a single Point then they just "touch". If it contains anything else (multiple Points and/or other polygons) then they overlap.

Edit: Now that I see your picture, you'll probably also need to use the disjoint method in addition to touches.

like image 182
Turix Avatar answered Sep 21 '22 18:09

Turix


This is the solution that worked for the OP (taken from question):

if ((pol1.intersects(pol2) == False) and (pol1.disjoint(pol2) == True)) or ((pol1.intersects(pol2) == True) and (pol1.touches(pol2) == True)):
    allowed = True
elif (pol1.intersects(polMe) == True) and (pol1.disjoint(polMe) == False) and (pol1.touches(polMe) == False):
    allowed = False
like image 22
River Avatar answered Sep 21 '22 18:09

River