Rab*_*saf 4 python polygon point-in-polygon
我试图检测给定的点(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
Run Code Online (Sandbox Code Playgroud)
这是一个有多个选项的简单方法
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)
Run Code Online (Sandbox Code Playgroud)
在函数内使用:
语法: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
Run Code Online (Sandbox Code Playgroud)
使用 contains 函数:
语法:polygon.contains(point)
# Check if polygon contains p1
print(poly.contains(p1))
# True
# Check if polygon contains p2
print(poly.contains(p2))
# False
Run Code Online (Sandbox Code Playgroud)
使用触摸功能:
语法:polygon.touches(point)
poly1 = Polygon([(0, 0), (1, 0), (1, 1)])
point1 = Point(0, 0)
poly1.touches(point1)
# True
Run Code Online (Sandbox Code Playgroud)
如果你想加快这个过程,那么请使用
import shapely.speedups
shapely.speedups.enable()
Run Code Online (Sandbox Code Playgroud)
和
使用 Geopandas
参考: