使用cartopy进行国家几何点包含测试的问题可以在Polygon containment test in matplotlib artist找到。
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 找到,并生成以下用于测试英国地形包含性的概念证明:
![uk_containment](https://istack.dev59.com/IO6oa.webp)
你可能会对另一个工具 geopandas 感兴趣,因为这种包含性测试是它的核心功能之一。