Skip to content

Instantly share code, notes, and snippets.

@tkhoa2711
Created October 15, 2015 03:21
Show Gist options
  • Save tkhoa2711/5c1bac6b7ed7c6430ce5 to your computer and use it in GitHub Desktop.
Save tkhoa2711/5c1bac6b7ed7c6430ce5 to your computer and use it in GitHub Desktop.
Test if a point is inside a triangle
import numpy as np
def point_inside_triangle(p, a, b, c):
'''
Check whether point p is inside the triangle of (a,b,c).
'''
return same_side(p, a, b, c) \
and same_side(p, b, a, c) \
and same_side(p, c, a, b)
def same_side(p1, p2, x, y):
'''
Check if p1 and p2 stay within the same side of halves of plane divided by x and y.
p1
/
/
x ____________ y
\
p2
'''
cp1 = cross_product(y-x, p1-x)
cp2 = cross_product(y-x, p2-x)
return dot_product(cp1, cp2) >= 0
def vector(*args):
return np.array(args)
def dot_product(x, y):
return np.dot(x, y)
def cross_product(x, y):
return np.cross(x, y)
if __name__ == '__main__':
a = vector(1,1)
b = vector(3,2)
c = vector(2,4)
points = ( vector(*x) for x in ( (2,2), (2,3), (1,1), (2,4), (3,2), (1,3), (3,4)) )
print [ point_inside_triangle(p, a, b, c) for p in points ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment