(Python)使用shapely判斷:點(diǎn)是否在多邊形中

判斷點(diǎn)是否在多邊形中的多種方法

1 使用shapely判斷點(diǎn)是否在多邊形中

使用python里的shapely庫可以很方便地判斷一個(gè)點(diǎn)是否在多邊形中
它的特點(diǎn)是你可以diy點(diǎn)和多邊形。適用于點(diǎn)和多邊形都有自己構(gòu)建的情況
首先,要先在控制臺安裝shapely

pip install shapely

然后,在py文件中,構(gòu)建一個(gè)shapely中的點(diǎn):
坐標(biāo)(1,1)

import shapely.geometry
point = shapely.geometry.Point(1, 1)

然后,構(gòu)建一個(gè)多邊形:
這里要注意,我們的輸入是字典格式的,有兩個(gè)鍵,分別是'type'和'coordinates',在'coordinates'里是多邊形的邊緣上的邊的坐標(biāo)。

import shapely.geometry
poly_context = {'type': 'MULTIPOLYGON',
    'coordinates': [[[[0, 0], [0, 2], [2, 2], [2, 0]]]]}
poly_shape = shapely.geometry.asShape(poly_context)
poly_shape
構(gòu)建的多邊形.png

最后,判斷點(diǎn)是否在多邊形中:

print(poly_shape.intersects(point))
#輸出: True

2 結(jié)合shapefile判斷點(diǎn)是否在shp文件的多邊形中

這時(shí)候,我們的多邊形通過shp文件讀取,點(diǎn)是我們自己構(gòu)造的
要用到shapefile和shapely兩個(gè)庫
然后我這個(gè)情況是,shp文件中有多個(gè)多邊形,我可以判斷點(diǎn)是否在每一個(gè)多邊形中,簡單地說是用這個(gè)函數(shù):

geometry.Point(point).within(geometry.shape(shape))

詳細(xì)代碼如下,我寫了個(gè)循環(huán),對于shp文件中的每個(gè)shape,我都判斷一下,點(diǎn)是否在其中

import shapefile
import shapely.geometry as geometry
shp_path = './temp.shp'
sf = shapefile.Reader(shp_path)
point = [-73.98088709894267, 40.75348098873852]
    for i in range(len(shapes)):
        print(i, geometry.Point(point).within(geometry.shape(shapes[i])))

輸出:

0 False
1 False
2 False
...
6 False
7 False
8 False

3 結(jié)合geopandas判斷點(diǎn)是否在shp文件的多邊形中

關(guān)于geopandas的安裝,請參考:
https://blog.csdn.net/weixin_41608080/article/details/114494953
Mac用戶請參考:
https://blog.csdn.net/qq_39805362/article/details/122741171
這個(gè)的前提,依然是,你有一個(gè)shp文件
然后我們現(xiàn)在不用shapefile讀取shp文件,而是geopandas讀取,不得不說,geopandas是真的好用,可以之間看到shape具體是什么數(shù)據(jù):

import geopandas
shp_path = './temp.shp'
shp_df = geopandas.GeoDataFrame.from_file(shp_path, )
print(shp_df.head())

輸出:

   region_id                                           geometry
0          0  POLYGON ((-73.98089 40.75348, -73.98094 40.753...
1          1  POLYGON ((-73.94712 40.82590, -73.94761 40.825...
2          2  POLYGON ((-73.99260 40.72414, -73.99263 40.724...
3          3  POLYGON ((-73.95034 40.77556, -73.95080 40.774...
4          4  POLYGON ((-73.93131 40.85933, -73.93136 40.859...

真的就所見即所得,我這個(gè)shp文件也是有多個(gè)多邊形。
然后比如說我們判斷一個(gè)點(diǎn)是否在第一個(gè)多邊形中,直接使用within函數(shù)即可:

pnts = Point(3, 3)
print(pnts.within(shp_df.iloc[0]['geometry']))

輸出:

False

非常好用!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容