Python Shapely-查找两个多多边形的部分是否重叠

时间:2018-10-03 21:38:45

标签: python shapely

从Shapely文档中-是否有任何函数可以让我知道右侧的红色多面体与右侧的黄色多面体的某些部分重叠? enter image description here

1 个答案:

答案 0 :(得分:0)

知道得很好:

您可以对MultiPolygons应用相同的“谓词和关系”方法,而您可以将其以匀称(see documentation)应用于任何其他几何对象。

检查是否重叠:

要检查两个Multipolygon是否重叠,可以使用object.intersects(other)。请参见以下示例(虽然不是您图片中的MultiPolygons):

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))

返回

>>>True
>>>True

编辑:

显然,OP对重叠不感兴趣,但是“正在尝试找出红色的[multi]多边形是否具有与黄色的部分完全相同的坐标”。

在这种情况下,您可以遍历各个多边形并检查它们是否等于目标多边形之一:

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

对于将来:源代码比文档的屏幕快照对回答您的问题更有用。