我正在尝试检测给定点 (x,y) 是否位于 n*2 数组的多边形中。但似乎多边形边界上的某些点返回它不包括在内。
def point_inside_polygon(x,y,poly):
n = len(poly)
inside =False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xinters = (y-p1y)*(p2x-p1x)/float((p2y-p1y))+p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x,p1y = p2x,p2y
return inside
请您参考如下方法:
这里有一个简单的方法,有多个选项
from shapely.geometry import Point, Polygon
# Point objects(Geo-coordinates)
p1 = Point(24.952242, 60.1696017)
p2 = Point(24.976567, 60.1612500)
# Polygon
coords = [(24.950899, 60.169158), (24.953492, 60.169158), (24.953510, 60.170104), (24.950958, 60.169990)]
poly = Polygon(coords)
方法一:
在函数内使用:
语法:point.within(polygon)
# Check if p1 is within the polygon using the within function
print(p1.within(poly))
# True
# Check if p2 is within the polygon
print(p2.within(poly))
# False
方法二:
使用包含函数:
语法:polygon.contains(point)
# Check if polygon contains p1
print(poly.contains(p1))
# True
# Check if polygon contains p2
print(poly.contains(p2))
# False
检查点是否位于多边形的边界上:
使用touches函数:
语法:polygon.touches(point)
poly1 = Polygon([(0, 0), (1, 0), (1, 1)])
point1 = Point(0, 0)
poly1.touches(point1)
# True
如果你想加快这个过程,那么请使用
import shapely.speedups
shapely.speedups.enable()
和
利用 Geopandas
引用:
