Perimeter of a 2D convex hull in Python

萝らか妹 提交于 2021-02-10 20:46:29

问题


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

  1. What is area in scipy convex hull


来源:https://stackoverflow.com/questions/52403793/perimeter-of-a-2d-convex-hull-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!