Skip to main content
 首页 » 编程设计

python之获取创建 ConvexHull 的点的索引

2025年05月04日15JeffreyZhao

我正在尝试使用 scipy.spatial(来自 scipy.spatial import ConvexHull)绘制一系列点的凸包。

import pylab as pl 
from scipy.spatial import ConvexHull 
 
pl.figure()   
pl.hold(True)   
 
points = np.concatenate((x, y), axis=1) 
 
hull = ConvexHull(points) 
 
pl.plot(points[:,0], points[:,1], 'ro') 
 
for simplex in hull.simplices: 
    pl.plot(points[simplex,0], points[simplex,1], 'dk--')     

问题是我没有正确理解什么是 hull.simplices,我想找到位于凸包面上的点的索引,这样我就可以使用这些索引从 x 和 y 中获取点

请您参考如下方法:

在二维情况下,ConvexHull 对象的simplices 属性保存构成凸包线段的点的索引对。仅获取索引的一种方法是获取扁平化 simplices 数组的唯一元素。但请注意,这些点的顺序不会遵循集合周围的凸包。 (在 scipy 0.13.0 及更高版本中,您可以使用 vertices 属性获取索引;见下文。)

例如,

import numpy as np 
from scipy.spatial import ConvexHull 
import matplotlib.pyplot as plt 
 
 
# Generate some random points for the demo. 
np.random.seed(4321) 
pts = 0.1 + 0.8*np.random.rand(15, 2) 
 
ch = ConvexHull(pts) 
 
# hull_indices = ch.vertices   # This will work in the scipy 0.13 
hull_indices = np.unique(ch.simplices.flat) 
hull_pts = pts[hull_indices, :] 
 
plt.plot(pts[:, 0], pts[:, 1], 'ko', markersize=10) 
plt.plot(hull_pts[:, 0], hull_pts[:, 1], 'ro', alpha=.25, markersize=20) 
plt.xlim(0, 1) 
plt.ylim(0, 1) 
plt.show() 

这会产生:

在 scipy 0.13.0 中添加了 vertices 属性:

import numpy as np 
from scipy.spatial import ConvexHull 
import matplotlib.pyplot as plt 
 
 
# Generate some random points for the demo. 
np.random.seed(4321) 
pts = 0.1 + 0.8*np.random.rand(15, 2) 
 
ch = ConvexHull(pts) 
 
# Get the indices of the hull points. 
hull_indices = ch.vertices 
 
# These are the actual points. 
hull_pts = pts[hull_indices, :] 
 
plt.plot(pts[:, 0], pts[:, 1], 'ko', markersize=10) 
plt.fill(hull_pts[:,0], hull_pts[:,1], fill=False, edgecolor='b') 
plt.xlim(0, 1) 
plt.ylim(0, 1) 
plt.show()