在Shapely中从多边形中删除重复的点

时间:2018-03-16 21:53:32

标签: python geospatial polygon shapely

要从列表中删除重复列表,Python中有几种不错的方法 - for example

a = [[ 9.1514622, 47.1166004 ], [ 9.1513045, 47.1164599 ], [ 9.1516278, 47.1163001 ], [ 9.1517832, 47.1164408 ], [ 9.1514622, 47.1166004 ] ] 

print len(a) # 5
b_set = set(map(tuple,a))
b = map(list,b_set)
print len(b) # 4

但不幸的是,我不得不将我的列表转换为Shapely Polygon对象,我需要简化几何并执行其他一些地理功能。

from shapely.geometry import Polygon
a = [[[ 9.1514622, 47.1166004 ], [ 9.1513045, 47.1164599 ], [ 9.1516278, 47.1163001 ], [ 9.1517832, 47.1164408 ], [ 9.1514622, 47.1166004 ] ] ]
polys = [Polygon(item) for item in a] # convert list to polygon
print len(polys) # prints 5

This answer显示了如何从多边形列表中删除重复的多边形,但如何从点列表中删除重复点,作为一个Shapely多边形?

我想可以将它转换回列表,删除重复项,然后重新转换为Polygon。

但这似乎过于复杂。关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:2)

让我们以您问题中的数据为例。你有一个坐标列表:

L = [[ 9.1514622, 47.1166004 ], [ 9.1513045, 47.1164599 ], [ 9.1516278, 47.1163001 ], [ 9.1517832, 47.1164408 ], [ 9.1514622, 47.1166004 ]]

然后转换为Polygon

P = Polygon(L)

现在,L似乎是多余的,因为最后一点与第一点相同。但这实际上不是问题,因为否则Shapely会复制第一个点(为了关闭Polygon的边界)。您可以通过以下方式看到:

P = Polygon(L)
print(list(P.exterior.coords))
#[(9.1514622, 47.1166004), (9.1513045, 47.1164599), (9.1516278, 47.1163001), (9.1517832, 47.1164408), (9.1514622, 47.1166004)]

#now skip the last point
P = Polygon(L[:-1])
print(list(P.exterior.coords))
#[(9.1514622, 47.1166004), (9.1513045, 47.1164599), (9.1516278, 47.1163001), (9.1517832, 47.1164408), (9.1514622, 47.1166004)]

如果有一些重复点"内部" L,例如:

L = [[ 9.1514622, 47.1166004 ], [ 9.1513045, 47.1164599 ], [ 9.1513045, 47.1164599 ], [ 9.1516278, 47.1163001 ], [ 9.1517832, 47.1164408 ], [9.1514622, 47.1166004 ]]

然后可以使用simplify方法消除它,零容忍(为了不引入副作用):

print(list(Polygon(L).simplify(0).exterior.coords))
#[(9.1514622, 47.1166004), (9.1513045, 47.1164599), (9.1516278, 47.1163001), (9.1517832, 47.1164408), (9.1514622, 47.1166004)]