![](/img/trans.png)
[英]Calculating overlapping/intersecting area of two irregular polygons in 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.