打开图片查看以下代码的结果
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 只能提供标记为红色的点(仅限矩形的角点)。
答案 0 :(得分:0)
如果您确定凸包是一个完美的矩形,其边与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