繁体   English   中英

使用 GeoJson 减去所有相交多边形后计算最终多边形 - Python

[英]Calculating final polygon after subtracting all intersecting polygons using GeoJson - Python

我有一个多边形,例如“Jumeirah Islands Clusters”,如图所示。 我想从 Islands Cluster 中减去湖 1、湖 2 GeoJson 文件。 我尝试了以下解决方案,但无法创建最终的多边形。

我尝试了两次以获得所需的结果,但显示的 output 不是所需的,因为在最后一步中没有减去湖 2。

from shapely.geometry import Polygon, mapping

with open("file_polygon_1.geojson") as f:
    feature = json.load(f)

if feature["geometry"]["type"] == "Polygon":
    polygon_1 = Polygon([(coor[0], coor[1]) for coor in feature["geometry"]["coordinates"][0]])

with open("file_polygon_2.geojson") as f:
    feature_2 = json.load(f)

if feature_2["geometry"]["type"] == "Polygon":
    polygon_2 = Polygon([(coor[0], coor[1]) for coor in feature_2["geometry"]["coordinates"][0]])

new_geometry = mapping(polygon_2.difference(polygon_1)) 

new_feature = dict(type="Feature",id="",properties=dict(Name=""), geometry=dict(type=new_geometry["type"], coordinates=new_geometry["coordinates"]),
)

outjson = dict(type="FeatureCollection", features=[new_feature])

所有图片

我认为您可能会对difference方法/功能的工作方式感到困惑。 由于我无权访问您的 GeoJSON 文件,因此我无法真正给您一个准确的答案,所以我能做的最好的就是使用我自己的形状特征给您一个示例:

import shapely 

lake1 = shapely.geometry.Polygon([(0,0),(0,3),(3,3),(3,0)])
lake2 = shapely.geometry.Polygon([(2,2),(2,5),(5,5),(5,2)])
islands = shapely.geometry.Polygon([(1,1),(1,4),(4,4),(4,1)])

上面的代码将创建三个不同的几何形状,如下图所示:

示例中使用的形状特征

如果您想生成最终的几何图形,使岛屿减去湖泊,您可以通过两种不同的方式来完成。

使用集合术语,我们可以说:

Islands_Minus_Lakes = Islands - Lake1 - Lake2

这相当于:

Islands_Minus_Lakes = Islands - (Lake1 + Lake2)

在 python 中,你可以写这两个如下:

# Version 1 
islands_minus_lakes = (islands.difference(lake1)).difference(lake2)

# Version 2
islands_minus_lakes = (islands.difference(lake1.union(lake2)))

两种方法产生完全相同的结果:

差异后的结果

一旦你拥有了islands_minus_lakes object,你可以选择任何你想要的操作它。

绘图注意事项

如果您想知道,我使用geopandas库来 plot 我的结果:

import geopandas as gpd

# Creating GeoDataFrames for the plots
gdf = gpd.GeoDataFrame({'name':['lake1','lake2','islands'],
                        'geometry':[lake1,lake2,islands]})

gdf2 = gpd.GeoDataFrame({'name':['islands_minus_lakes'],
                         'geometry':[islands_minus_lakes]})

# Generates the plot of the inputs
gdf.plot(alpha=0.4)

# Generates the plot of the outputs
gdf2.plot(alpha=0.4)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM