【问题标题】:Get the distance of each point with every other, and find where the curve approach itself获取每个点之间的距离,并找到曲线接近自身的位置
【发布时间】:2017-12-18 11:06:46
【问题描述】:

我正在编程一个随机生成的样条曲线,首先生成控制点,然后用spicy.splev进行插值。Here就是一个例子。

积分如下:

np.array =[[  1.00000000e+01  -4.65000000e+02]
           [  1.78319153e+01  -4.60252579e+02]
          ...]

我现在想获取每个样条线的每个点的距离,以查看样条线是否在某一点过于靠近自身,包括自碰撞。

在每个点之前和之后应该有一个间隔,点被忽略,因为这些点总是离每个点最近的点:

def collision(splinePoints, interval):
    length = len(splinePoints)    
    mylist = []
    i = -1
    for item in splinePoints:
        i += 1
        first = item
        lowerLimit = i - interval
        uperLimit = i + interval
        if lowerLimit >= 0:
            for item in splinePoints[:lowerLimit]:
                mylist.append(first)
                mylist.append(item)
        if uperLimit <= length:
            for item in splinePoints[uperLimit:]:
                mylist.append(first)
                mylist.append(item)
    return np.amin(lengthOfLines(np.array(mylist)))

用这个检查行的长度:

def lengthOfLines(points):
    return np.sqrt(np.sum(np.diff(points.T)**2, axis=0))

它以某种方式起作用,但并非总是如此。我也在努力调试,因为生成的数据很大并且难以阅读检查或比较。知道如何做得更好吗?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    所有成对距离都是使用 scipy.spatial 包的pdist 方法获得的。它返回一个平坦的距离数组,消除了冗余。实用函数squareform 将它们解压缩为对称方阵,这通常更方便。

    您还希望找到不直接位于曲线上给定点之前或之后的最近点。在下面的示例中,我通过将这些距离设置为无穷大来惩罚邻居之间的距离(在 20 个索引值内)。然后argmin为每个人找到最近的点,我通过在最近的点上画一条红线来可视化它。

    import numpy as np
    from scipy.spatial.distance import pdist, squareform
    
    t = np.linspace(0, 10, 50)
    points = np.stack(((t+5)*np.cos(t), (t+5)*np.sin(t)), axis=-1)  # for example
    
    distances = squareform(pdist(points))    # distance matrix
    i, j = np.meshgrid(np.arange(t.size), np.arange(t.size))
    distances[np.abs(i-j) <= 20] = np.inf    # don't count neighbors
    nearest = np.argmin(distances, axis=0)   # nearest to each
    
    plt.plot(points[:, 0], points[:, 1])
    for k in range(len(t)):
      npoint = points[nearest[k]]
      plt.plot([points[k, 0], npoint[0]], [points[k, 1], npoint[1]], 'r')
    plt.axes().set_aspect('equal', 'datalim')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 2021-08-02
      • 1970-01-01
      相关资源
      最近更新 更多