how can I calculate the centroid of a convex hull using python and scipy? All I found are methods for computing Area and Volume.
regards,frank.
Assuming you have constructed the convex hull using scipy.spatial.ConvexHull
, the returned object should then have the positions of the points, so the centroid may be as simple as,
import numpy as np
from scipy.spatial import ConvexHull
points = np.random.rand(30, 2) # 30 random points in 2-D
hull = ConvexHull(points)
#Get centoid
cx = np.mean(hull.points[hull.vertices,0])
cy = np.mean(hull.points[hull.vertices,1])
Which you can plot as follows,
import matplotlib.pyplot as plt
#Plot convex hull
for simplex in hull.simplices:
plt.plot(points[simplex, 0], points[simplex, 1], 'k-')
#Plot centroid
plt.plot(cx, cy,'x',ms=20)
plt.show()
The scipy convex hull is based on Qhull which should have method centrum, from the Qhull docs,
A centrum is a point on a facet's hyperplane. A centrum is the average of a facet's vertices. Neighboring facets are convex if each centrum is below the neighbor facet's hyperplane.
where the centrum is the same as a centroid for simple facets,
For simplicial facets with d vertices, the centrum is equivalent to the centroid or center of gravity.
As scipy doesn't seem to provide this, you could define your own in a child class to hull,
class CHull(ConvexHull):
def __init__(self, points):
ConvexHull.__init__(self, points)
def centrum(self):
c = []
for i in range(self.points.shape[1]):
c.append(np.mean(self.points[self.vertices,i]))
return c
hull = CHull(points)
c = hull.centrum()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With