Created
October 15, 2015 03:21
-
-
Save tkhoa2711/5c1bac6b7ed7c6430ce5 to your computer and use it in GitHub Desktop.
Test if a point is inside a triangle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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