I'm trying to make a function that will return True
if the given (x,y) point is inside a convex polygon. I'm trying to make it without numpy or any similar imports, just pure python code.
I've already found a sample solution, which seems OK at first sight, but it's not working correctly, and I can't figure out why. The code is as follows:
def point_in_poly(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:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
If I test it for (9,9), for the following polygon, it gives me True
:
polygon = [(0,10),(10,10),(10,0),(0,0)]
point_x = 9
point_y = 9
print point_in_poly(point_x,point_y,polygon)
But when I change the order of the points of the polygon, for the same point, it gives me False
:
polygon = [(0,0), (0,10), (10,0), (10,10)]
point_x = 9
point_y = 9
print point_in_poly(point_x,point_y,polygon)
Anybody knows the reason? Thanks!