打开图像以查看以下代码的结果
import numpy as np
from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt
points = np.array([[1,1],[1,2],[1,3],[1,4],[2,1],[2,2],[2,3],[2,4],[3,1],[3,2],[3,3],[3,4],[4,1],[4,2],[4,3],[4,4]])
hull = ConvexHull(points)
plt.plot(points[:,0], points[:,1], 'o')
for simplex in hull.simplices:
plt.plot(points[simplex, 0], points[simplex, 1], 'k-')
plt.plot(points[simplex,0], points[simplex,1], 'ro', alpha=.25, markersize=20)
我想获取凸包上的点坐标索引(黑色+线上的点(。我选择矩形只是为了得到一个极端的情况。
hull.points只能给出标记为红色的点(只有矩形的角点(。
代码的结果
如果您确定凸包是一个完美的矩形,其边与 x 轴和 y 轴对齐,则查找所有边界点的索引非常简单。根本不需要计算凸包来执行此操作。该描述符合您的示例。下面是一些在这种情况下执行所需操作的代码。此代码的时间复杂度O(n)
其中n
是总体点数。
# Find the indices of all boundary points, in increasing index order,
# assuming the hull is a rectangle aligned with the axes.
x_limits = (min(pt[0] for pt in points), max(pt[0] for pt in points))
y_limits = (min(pt[1] for pt in points), max(pt[1] for pt in points))
boundary_indices = [idx for idx, (x, y) in enumerate(points)
if x in x_limits or y in y_limits]
但是,这种情况似乎很简单。以下是适用于所有二维情况的更通用的代码,尤其是当点具有积分坐标时。这是因为如果精度不精确,则查找点是否正好在线段上是很棘手的。该代码以时间复杂度O(n*m)
运行,其中n
是点数,m
是凸包中的顶点数。
# Find the indices of all boundary points, in increasing index order,
# making no assumptions on the hull.
def are_collinear2d(pt1, pt2, pt3):
"""Return if three 2-dimensional points are collinear, assuming
perfect precision"""
return ((pt2[0] - pt1[0]) * (pt3[1] - pt1[1])
- (pt2[1] - pt1[1]) * (pt3[0] - pt1[0])) == 0
vertex_pairs = list(zip(vertices, vertices[1:] + vertices[0:1]))
boundary_indices = []
for idx, pt in enumerate(points):
for v1, v2 in vertex_pairs:
if are_collinear2d(pt, v1, v2):
boundary_indices.append(idx)
break