pythonscipyconvex-hullqhull

SciPy.spatial: How to use ConvexHull with points containing an attribute?


Having a list of points (x, y), the function ConvexHull() of SciPy.spatial is great to calculate the points that form the hull.

In my case, every point (x, y) also has a string as attribute. Is it possible to calculate the hull and returning its points including their respective attribute (x, y, str)?

I checked both https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html as well as http://www.qhull.org/html/qh-optq.htm, but could not find a solution.

Here, an example where I would like to run the commented lines with points_with_attribute instead of points_no_attribute:

from scipy.spatial import ConvexHull

points_no_attribute = [(0, 0), (2, 6), (6, 1), (2, 4), (3, 2)]
points_with_attribute = [(0, 0, "point1"), (2, 6, "point2"), (6, 1, "point3"), (2, 4, "point4"), (3, 2, "point5")]

hull = ConvexHull(points_no_attribute)
hull_points = [points_no_attribute[i] for i in hull.vertices]

# hull = ConvexHull(points_with_attribute)
# hull_points = [points_with_attribute[i] for i in hull.vertices]

print(hull_points)

Thanks for a hint!


Solution

  • I would suggest:

    hull = ConvexHull([(p[0], p[1]) for p in points_with_attribute])
    hull_points = [points_with_attribute[i] for i in hull.vertices]
    

    This has the advantage of avoiding an O(N^2) loop, by using the index of the points that has already been found.