I searched a lot and cant find any practical answer to my question. I have a polygon. For example:
[(86, 52), (85, 52), (81, 53), (80, 52), (79, 48), (81
Try this code. poly_coords are the coordinates of your polygon, 'coord' is coordinate of point you want to check if it is inside the polygon.
def testP(coord, poly_coords):
"""
The coordinates should be in the form of list of x and y
"""
test1 = n.array(poly_coords)
test2 = n.vstack((poly_coords[1:], poly_coords[:1]))
test = test2-test1
m = test[:,1]/test[:,0]
c = test1[:,1]-m*test1[:,0]
xval = (coord[1]-c)/m
print 'xVal:\t'; print xval
print (test1[:,0]-xval)*(test2[:,0]-xval)
check = n.where((xval>=coord[0])&((test1[:,0]-xval)*(test2[:,0]-xval)<0))[0]
print check
print len(check)
if len(check)%2==0:
return False
else:
return True
If you want to make it even faster, take out the part of algo related to polygon, slope and offset and run the rest of code using 'map' function. Something like this:
test1 = n.array( your polygon)
test2 = n.vstack((test1[1:], test1[:1]))
test = test2-test1
m = test[:,1]/test[:,0]
c = test1[:,1]-m*test1[:,0]
def testP(coord):
"""
The coordinates should be in the form of list of x and y
"""
global test, test1, test2, m,c
xval = (coord[1]-c)/m
check = n.where((xval>=coord[0])&((test1[:,0]-xval)*(test2[:,0]-xval)<0))[0]
if len(check)%2==0:
return False
else:
return True
coords = n.array(( your coords in x,y ))
map (testP, coords)
You can remove 'print' commands if you want. This code is made for python 2.7