Gursel Karacor
Gursel Karacor

Reputation: 1167

Perimeter of a 2D convex hull in Python

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.

Upvotes: 1

Views: 2431

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61930

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

Upvotes: 2

Related Questions