我试图检测给定点(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
您可以使用来自
matplotlib.path
的contains_point
函数,并具有较小的负半径和正半径(小技巧)。像这样:结果是
^{pr2}$默认情况下(或
r=0
)不包括边界上的所有点,结果是以下是包含边缘的正确代码:
更新:修复了一个错误
相关问题 更多 >
编程相关推荐