可以在Polygon containment test in matplotlib artist 找到有关使用 cartopy 对国家几何图形进行点包含测试的问题。
Cartopy 有实现这一点的工具,但没有“is_land”等内置方法。相反,您需要获取适当的几何数据,并使用标准的 shapely 谓词进行查询。
import cartopy.io.shapereader as shpreader
import shapely.geometry as sgeom
from shapely.ops import unary_union
from shapely.prepared import prep
land_shp_fname = shpreader.natural_earth(resolution='50m',
category='physical', name='land')
land_geom = unary_union(list(shpreader.Reader(land_shp_fname).geometries()))
land = prep(land_geom)
def is_land(x, y):
return land.contains(sgeom.Point(x, y))
这给出了两个样本点的预期结果:
>>> print(is_land(0, 0))
False
>>> print(is_land(0, 10))
True
如果您可以访问它,fiona 将使这更容易(而且更快捷):
import fiona
import cartopy.io.shapereader as shpreader
import shapely.geometry as sgeom
from shapely.prepared import prep
geoms = fiona.open(
shpreader.natural_earth(resolution='50m',
category='physical', name='land'))
land_geom = sgeom.MultiPolygon([sgeom.shape(geom['geometry'])
for geom in geoms])
land = prep(land_geom)
最后,我(早在 2011 年)制作了 shapely.vectorized 功能,以在同时测试 许多 点时加速这种操作。该代码可在https://gist.github.com/pelson/9785576 上作为要点获得,并为英国测试土地遏制产生以下概念验证:
您可能有兴趣阅读的另一个工具是 geopandas,因为这种遏制测试是它的核心功能之一。