Yair
Yair

Reputation: 909

Python Shapely - find if parts of two multi polygons overlap

From the Shapely documentation - is there any function that can let me know that the red multipolygon on the right overlaps some parts of the yellow multiplolygon on the right? enter image description here

Upvotes: 1

Views: 4428

Answers (1)

elpunkt
elpunkt

Reputation: 304

Good to know:

You can apply the same "Predicates and Relationships" methods on MultiPolygons that you can apply on any other Geometric Object in shapely (see documentation).

Check for overlapping:

To check if two Multipolygons overlap you can use object.intersects(other). See this example (not the MultiPolygons from your picture though):

from shapely.geometry import MultiPolygon
a = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]
b = [(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)]

multi1 = MultiPolygon([[a, []], [b, []]])

c = [(0, 1.5), (1.5, 1.5), (1.5, 3), (0, 3), (1.5, 3)]
d = [(1.5, 1.5), (1.5, 0), (3, 0), (3, 1.5), (1.5, 1.5)]

multi2 = MultiPolygon([[c, []], [d, []]])

print(multi1.intersects(multi2))
print(multi2.intersects(multi1))

Returns

>>>True
>>>True

Edit:

Apparently, OP is not interested in overlapping, but is "trying to find out if the red [multi]polygon has the exact same coordinates as parts of the yellow one".

In that case you can iterate over the individual Polygons and check if they are equal to one of the target Polygons:

from shapely.geometry import MultiPolygon
#target multipolygon
a = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]
b = [(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)]
c = [(2, 1), (3, 1), (3, 0), (2, 0), (2, 1)]
multi_target = MultiPolygon([[a, []], [b, []], [c, []]])

#test multipolygon with two polygons that match a target polygon
a = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]
b = [(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)]
multi_test1 = MultiPolygon([[a, []], [b, []]])

#test multipolygon where one polygon does not exactly match a target polygon.
a = [(0, 0.5), (0, 1), (1, 1), (1, 0.5), (0, 0.5)]
b = [(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)]
multi_test2 = MultiPolygon([[a, []], [b, []]])

def check_multipolys(test, target):
    for test_poly in test:
        exists = False
        for target_poly in target:
            if test_poly.equals(target_poly):
                exists = True
                break
        if not exists:
            return False
    return True

>>>check_multipolys(multi_test1, multi_target)
>>>True
>>>check_multipolys(multi_test2, multi_target)
>>>False

For the future: the source code would have been more helpful to answer your question, than a screenshot of the documentation.

Upvotes: 2

Related Questions