bjornasm
bjornasm

Reputation: 2328

Check if points lies inside a convex hull

I am making a convex hull using the scipy.spatial package http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html#scipy.spatial.ConvexHull

I've tried searching, but have yet to know if there is an easy way to find if any point (latitude/longitude) lies inside the convex hull. Any suggestions?

Upvotes: 12

Views: 6413

Answers (2)

lmjohns3
lmjohns3

Reputation: 7602

The matplotlib Path method works, but only for 2-dimensional data. A general method that works in arbitrary dimensions is to use the halfspace equations for the facets of the hull.

import numpy as np
from scipy.spatial import ConvexHull

# Assume points are shape (n, d), and that hull has f facets.
hull = ConvexHull(points)

# A is shape (f, d) and b is shape (f, 1).
A, b = hull.equations[:, :-1], hull.equations[:, -1:]

eps = np.finfo(np.float32).eps

def contained(x):
  # The hull is defined as all points x for which Ax + b <= 0.
  # We compare to a small positive value to account for floating
  # point issues.
  #
  # Assuming x is shape (m, d), output is boolean shape (m,).
  return np.all(np.asarray(x) @ A.T + b.T < eps, axis=1)

# To test one point:
print('Point (2,1) is in the hull?', contained([[2, 1]]))

Upvotes: 6

Simon Gibbons
Simon Gibbons

Reputation: 7194

The method that I've used before is using the Path class matplotlib. This has a contains_point method which does exactly that. As well as a contains_points which allows you to query an array of points.

To use this you would do

from scipy.spatial import ConvexHull
from matplotlib.path import Path

hull = ConvexHull( points )

hull_path = Path( points[hull.vertices] )

print hull_path.contains_point((1,2)) # Is (1,2) in the convex hull?

Upvotes: 22

Related Questions