Skip to content

Instantly share code, notes, and snippets.

@petrushev
Created April 23, 2013 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petrushev/5448472 to your computer and use it in GitHub Desktop.
Save petrushev/5448472 to your computer and use it in GitHub Desktop.
Determine if a point is inside a given polygon or not Polygon is a list of (x,y) points. Uses the 'Ray Casting' algorithm
def is_inside(polygon, point):
"""Determine if a point is inside a given polygon or not
Polygon is a list of (x,y) points.
Uses the 'Ray Casting' algorithm"""
x, y = point
n = len(polygon)
inside = False
p1x, p1y = polygon[0]
for i in range(n + 1):
p2x, p2y = polygon[i % n]
if y > min(p1y, p2y) and y <= max(p1y, p2y) and 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
def test():
polygon = [(0,10),(10,10),(10,0),(0,0)]
assert is_inside(polygon, (5, 5))
assert is_inside(polygon, (0.1, 0.1))
assert not is_inside(polygon, (0, 0))
assert not is_inside(polygon, (11, 4))
assert is_inside(polygon, (9.9, 9.9))
assert is_inside(polygon, (9, 10))
assert is_inside(polygon, (10, 9))
polygon = [(0, 0), (2, 0), (2, 1)]
assert is_inside(polygon, (1, 0.4))
assert not is_inside(polygon, (1, 0.6))
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment