与其使用 cascaded_union 方法,不如编写自己的方法来检查两个多边形是否相交可能更容易。如果我理解您想要正确执行的操作,您想查找两个多边形是否重叠,然后删除其中一个并相应地编辑另一个。
你可以这样(不是最好的解决方案,我会解释为什么):
def clean_closely_lying_points(nodes):
polygons = [Point([nodes[i]).buffer(1) for i in range(len(nodes))]
for i in range(len(polygons) - 1):
if polygons[i] is None:
continue
for j in range(i + 1, len(polygons)):
if polygons[j] is None:
continue
if polygons[i].intersects(polygons[j]):
polygons[j] = None
nodes[j] = None
# now overwrite 'i' so that it's whatever you want it to be, based on the fact that polygons[i] and polygons[j] intersect
polygons[i] =
nodes[i] =
然而,总的来说,我觉得多边形的创建是耗时且不必要的。同时更新多边形列表和节点列表也很乏味。相反,您可以只使用节点本身,并使用 shapely 的距离方法来检查两个点是否在彼此的 2 个单位内。这在数学上应该是等价的,因为两个半径均为 1 的圆之间的交点意味着它们的中心点至多相距 2。在这种情况下,您的 for 循环将采用类似的结构,但它们会遍历节点。
def clean_closely_lying_points(nodes):
point_nodes = [Point(node) for node in nodes] # Cast each of the nodes (which I assume are in tuple form like (x,y), to shapely Points)
for i in range(len(point_nodes) - 1):
if point_nodes[i] is None:
continue
for j in range(i + 1, len(point_nodes)):
if point_nodes[j] is None:
continue
if point_nodes[i].distance(point_nodes[j]) < 2:
point_nodes[j] = None
point_nodes[i] = # Whatever you want point_nodes[i] to be now that you know that point_nodes[j] was within a distance of 2 (could remain itself)
return [node for node in point_nodes if node is not None]
这种方法的结果将是一个匀称的点对象列表,消除了靠近的点。