我在这里看到了一个可靠的算法,可以检查一个点是否在多边形内。
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) / (p2y - p1y) + p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y
return inside
好吧,我用点和多边形检查了它:
point_inside_polygon(0.3,0.5,[(0.5,0),(1,0.5),(0.5,1),(0,0.5)])
point_inside_polygon(0.3,1,[(0.5,0),(1,0.5),(0.5,1),(0,0.5)])
当然输出是正确的:
True,False
然后我尝试自己使用它,我可以做的最微小的改变使它适合我的程序:
class Point2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
def __repr__(self):
return self.__str__()
class Polygon2D:
def __init__(self, pts):
self.points = pts
def __repr__(self):
return str(self.points)
def is_inside(self, q):
n = len(self.points)
inside = False
p1x, p1y = self.points[0]
for i in range(n + 1):
p2x, p2y = self.points[i % n]
if q.y > min(p1y, p2y):
if q.y <= max(p1y, p2y):
if q.x <= max(p1x, p2x):
if p1y != p2y:
xinters = (q.y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
if p1x == p2x or q.x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y
return inside
当我尝试时:
p.is_inside(Point2D(0.3, 0.5))
p.is_inside(Point2D(0.3, 1))
输出错误:假,真。
帮助?