通过减去与另一个多边形的交点来创建新的形状多边形

Create new shapely polygon by subtracting the intersection with another polygon

我有两个相交于不同部分的形状匀称的 MultiPolygon 实例(由经度、纬度点组成)。我正在尝试循环,确定两个多边形之间是否存在交集,然后创建一个排除该交集的新多边形。从附图来看,我基本上不希望红色圆圈与黄色轮廓重叠,我希望边缘恰好位于黄色轮廓开始的位置。

我已经尝试按照说明进行操作 here 但它根本没有改变我的输出,而且我不想将它们合并为一个级联联合体。我没有收到任何错误消息,但是当我将这些 MultiPolygons 添加到 KML 文件时(只是 python 中的原始文本操作,没有花哨的程序)它们仍然显示为圆圈,没有任何修改。

# multipol1 and multipol2 are my shapely MultiPolygons
from shapely.ops import cascaded_union
from itertools import combinations
from shapely.geometry import Polygon,MultiPolygon

outmulti = []
for pol in multipoly1:
    for pol2 in multipoly2:
        if pol.intersects(pol2)==True:
            # If they intersect, create a new polygon that is
            # essentially pol minus the intersection
            intersection = pol.intersection(pol2)
            nonoverlap = pol.difference(intersection)
            outmulti.append(nonoverlap)

        else:
            # Otherwise, just keep the initial polygon as it is.
            outmulti.append(pol)

finalpol = MultiPolygon(outmulti)

我想你可以使用这两个多边形之间的 symmetric_difference,结合与第二个多边形的差异来实现你想要做的(对称差异将为您带来两个多边形的非重叠部分,其中删除了多边形 2 的部分 差异 )。我没有测试过,但它可能看起来像:

# multipol1 and multipol2 are my shapely MultiPolygons
from shapely.ops import cascaded_union
from itertools import combinations
from shapely.geometry import Polygon,MultiPolygon

outmulti = []
for pol in multipoly1:
    for pol2 in multipoly2:
        if pol.intersects(pol2)==True:
            # If they intersect, create a new polygon that is
            # essentially pol minus the intersection
            nonoverlap = (pol.symmetric_difference(pol2)).difference(pol2)
            outmulti.append(nonoverlap)

        else:
            # Otherwise, just keep the initial polygon as it is.
            outmulti.append(pol)

finalpol = MultiPolygon(outmulti)