LoginSignup
1
0

More than 5 years have passed since last update.

Polygon-point containment in Python

Posted at
def contains(g, p): 
  n = len(g)
  x = False
  for i in range(n):
    a = np.array(g[i]) - np.array(p)
    b = g[(i+1)%n] - p 
    if (np.linalg.norm(np.cross(a,b)) < np.finfo(np.float).eps \
        and np.dot(a,b) < np.finfo(np.float).eps):
        return 1
    if (a[1] > b[1]):
        b,a = a,b 
    if (a[1] < np.finfo(np.float).eps and np.finfo(np.float).eps < b[1] \
        and np.cross(a,b) > np.finfo(np.float).eps):
        x = not(x)
  if (x):
      return 2
  return 0

g = []
n = input()
for i in range(n):
    a = []
    a.append(map(int, raw_input().split()))
    for aa in a:
        x = aa[0]
        y = aa[1]
        g.append([x,y])
#print(g)
n = input()
for i in range(n):
    a = []
    a.append(map(int, raw_input().split()))
    for aa in a:
        x = aa[0]
        y = aa[1]
        ret = contains(np.array(g), np.array([x,y]))
        print(ret)
4
0 0
3 1
2 3
0 3
3
2 1
2
0 2
1
3 2
0

Refs.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0