-2

打开图像以查看以下代码的结果

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只能给出标记为红色的点(仅矩形的角点)。

代码结果

4

1 回答 1

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
于 2018-06-17T20:42:12.983 回答