Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 528
bjornasm Avatar asked Jul 14 '15 10:07

bjornasm


2 Answers

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]]))
like image 190
lmjohns3 Avatar answered Sep 29 '22 17:09

lmjohns3


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?
like image 27
Simon Gibbons Avatar answered Sep 29 '22 16:09

Simon Gibbons