Skip to content

Instantly share code, notes, and snippets.

@izderadicka
Created November 29, 2015 07:58
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 izderadicka/01518a5c1a8b8fdbcdfe to your computer and use it in GitHub Desktop.
Save izderadicka/01518a5c1a8b8fdbcdfe to your computer and use it in GitHub Desktop.
Check if point is inside triangle
import matplotlib.pyplot as lpt
import numpy as np
def pt(data, point=None):
p = plt.Polygon(data, closed=True, fill=None)
ax = plt.gca()
ax.add_patch(p)
x=data[:,0]
y=data[:,1]
if point:
x=x
y=y
ax.set_xlim(x.min()-1,x.max()+1)
ax.set_ylim(y.min()-1,y.max()+1)
if point:
plt.plot(point[0], point[1], 'xr', markersize=20)
def cross(a,b):
'#cross product of two 2d vectors'
return a[0]*b[1] - a[1]*b[0]
def inside(p, t):
'Is point p inside triangle y'
def test(a,b,c):
'''test if cross product BA x PA and BA x BC has same sign,
this mean that P is on same side as C - towards the triangle inside '''
u=cross(t[b]-t[a], p-t[a])
v=cross(t[b]-t[a], t[c]-t[a])
return u*v >= 0 # if 0 then P is BA line
# for point to be inside triagle it must lay inside relative to all three sides
return test(0,1,2) and test(1,2,0) and test(2,0, 1)
t=np.array([[0,0], [10,0], [5,10]])
p=[5,5]
pt(t, p)
print 'P is inside', inside(p,t)
p2=[10,4]
plt.plot(p2[0], p2[1], 'og')
print 'P2 is inside', inside(p2,t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment