问题
How can I calculate the perimeter of a convex hull in Python? I know SciPy
has the area
parameter for convex hulls; however, I need the perimeter
.
回答1:
You can iterate over the points of the convex hull and compute the distance between consecutive points:
import numpy as np
from scipy.spatial.qhull import ConvexHull
from scipy.spatial.distance import euclidean
points = np.random.rand(30, 2)
hull = ConvexHull(points)
vertices = hull.vertices.tolist() + [hull.vertices[0]]
perimeter = np.sum([euclidean(x, y) for x, y in zip(points[vertices], points[vertices][1:])])
print(perimeter)
Output
3.11
Note: You also need to add the pair (last, first)
UPDATE
As an alternative, given that the data is 2D, you can use hull.area
. That is the value returned in the above method is equal to the value of the area property. If you want the real area, you need to query hull.volume
.
Further
- What is area in scipy convex hull
来源:https://stackoverflow.com/questions/52403793/perimeter-of-a-2d-convex-hull-in-python