检查 Point 对象是否在 Polygon 内时出现 Shapely 断言错误

Shapely assertion error when checking if a Point object is within a Polygon

我有一本地名字典和相关的多边形几何图形。

geom_dict = {'Hanford-Corcoran, CA': 'POLYGON((-119.958925 36.255468, -119.958911 36.254885, -119.958886 36.253897, -119.958853 36.251897, -119.958907 36.249703, -119.958896 36.248311.......))}

我写了一个函数来检查Polygon中是否存在一个Point并获取对应地点的名字

def poly_lookup(long, lat, geom_dict):
    # Iterate over dict of market and polygon geom. 
    # Check if the point lies within polygon, if true, get the market. 

    for key, val in geom_dict.items():

        point = Point(long, lat)
        polygon = Polygon(val)
    
        if point.within(polygon):
        
           return key

但是,当我调用此函数时,出现断言错误。

    File "/Users/", line 169, in
    market = poly_lookup(Lat, Long, geom_dict)
  File "/Users/polygon.py", line 76, in market_Lookup
    polygon = Polygon(val)
  File "/Users/anaconda3/lib/python3.8/site-packages/shapely/geometry/polygon.py", line 243, in __init__
    ret = geos_polygon_from_py(shell, holes)
  File "/Users/kevalshah/opt/anaconda3/lib/python3.8/site-packages/shapely/geometry/polygon.py", line 509, in geos_polygon_from_py
    ret = geos_linearring_from_py(shell)
  File "shapely/speedups/_speedups.pyx", line 343, in shapely.speedups._speedups.geos_linearring_from_py
AssertionError

错误是由于您实例化 polygon 变量的方式造成的。 Polygon 构造函数不将 wkt 字符串作为参数,它需要坐标元组列表,更准确地说:

The Polygon constructor takes two positional parameters. The first is an ordered sequence of (x, y[, z]) point tuples and is treated exactly as in the LinearRing case. The second is an optional unordered sequence of ring-like sequences specifying the interior boundaries or “holes” of the feature.

(source: https://shapely.readthedocs.io/en/stable/manual.html#Polygon)

要读取 wkt 字符串,您必须使用 shapely.wkt 模块:

from shapely import wkt

您可以在代码中像这样使用:

polygon = wkt.loads(val)

其中 val 包含 wkt 字符串。