使用shapely判断点是否在多边形内?

7
我正在运行以下脚本,我认为应该返回点在多边形内的TRUE,但它返回的是FALSE。
from shapely import geometry

polygon = [(-1571236.8349707182, 8989180.222117377), (1599362.9654156454, 8924317.946336618), (-1653179.0745812152, 8922145.163675062), (-1626237.6614402141, 8986445.107619021)]

Point_X = -1627875.474
Point_Y = 8955472.968

line = geometry.LineString(polygon)
point = geometry.Point(Point_X, Point_Y)

print(line.contains(point))

当我在Matlab中绘制多边形和点时,我得到了以下形状。

enter image description here

from matplotlib import pylab as plt
poly = [[-1571236.8349707182, 8989180.222117377],
    [1599362.9654156454, 8924317.946336618],
    [-1653179.0745812152, 8922145.163675062],
    [-1626237.6614402141, 8986445.107619021]]

x = [point[0] for point in poly]
y = [point[1] for point in poly]

p1 = [-1627875.474, 8955472.968]
p2 = [-1627875.474, 8955472.968]
plt.plot(x,y,p1[0],p1[1],'*r',p2[0],p2[1],'*b')
plt.show()

有任何想法为什么这个优美的脚本会返回 FALSE 吗?

可能是因为你的形状没有闭合。它不知道它是凸还是凹,所以它无法真正地根据你提供的内容创建一个形状。你可能需要确保它在同一点开始和结束。 - Qwerty
我尝试过了 - 不幸的是,当我将起始点作为第五个坐标添加时,我得到了相同的答案(FALSE)。 - user2512696
2个回答

19

您正在测试的是点是否在对象LineString上。

如果您想测试该点是否在多边形内,必须使用Polygon类的contains方法。

from shapely import geometry

polygon = [(-1571236.8349707182, 8989180.222117377), (1599362.9654156454, 8924317.946336618), (-1653179.0745812152, 8922145.163675062), (-1626237.6614402141, 8986445.107619021)]

Point_X = -1627875.474
Point_Y = 8955472.968

line = geometry.LineString(polygon)
point = geometry.Point(Point_X, Point_Y)
polygon = geometry.Polygon(line)

print(polygon.contains(point))

输出

True

请参阅 https://shapely.readthedocs.io/en/latest/manual.html


太好了!非常感谢——我误解了LineString对象。 - user2512696

0
这段代码使用geopandas来找到在多边形内的点。
import geopandas as gpd
points_gpd = gpd.GeoDataFrame(geometry=gpd.points_from_xy(x, y)) #point coordinates to geopandas dataframe
polygons_gpd = gpd.GeoDataFrame(geometry=polygons) #polygons is a list of shapely polygons
pt2poly = gpd.sjoin(points_gpd,polygons_gpd, predicate='within').index_right #for each point index in the points, it stores the polygon index containing that point

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接