【问题标题】:Speeding up selecting sets of 3 nodes that form triangles with given min and max side length加快选择形成具有给定最小和最大边长的三角形的 3 个节点集
【发布时间】:2014-11-30 10:31:13
【问题描述】:

我有一个大约 60 个点的列表,我从中生成所有可能的大小为 3 的组合。我试图确定这 3 个点中的任何一个是否在特定距离参数内 - 也就是说,不是太彼此靠近,并且彼此之间的距离不太远(例如,任何点与下一个最近点的距离不得小于 10 个单位,任何点与最远的点之间的距离不得超过 100 个单位)。

我在这里有代码:

def setPalmCombinations(self):
    # Testing confirms that the range of distances is about 5 - 10 for
    # minimum distance between points, and anywhere from 150 - 200 for max
    # distance between points. 10 and 100 should be reasonable cutoffs.
    minDistance = 10
    maxDistance = 100
    startTime = time.time()
    iter = itertools.combinations(self.handContour, 3)
    def distanceCheck(points):
        A = points[0][0]
        B = points[1][0]
        C = points[2][0]
        AB = np.linalg.norm(A - B)
        if not(minDistance < AB < maxDistance): return None
        BC = np.linalg.norm(B - C)
        if not(minDistance < BC < maxDistance): return None
        CA = np.linalg.norm(C - A)
        if not(minDistance < CA < maxDistance): return None
        return np.array([A, B, C])
    a = [distanceCheck(i) for i in iter]
    print time.time() - startTime

但是,仅生成此可能组合列表大约需要 0.4 到 0.5 秒,这太慢了。有没有办法我可以优化这个计算(或者从根本上重做算法,使它不仅仅是一个蛮力搜索),这样我就可以把时间缩短到大约实时计算(即每秒 30 次)。

我正在考虑可能生成每个点之间的距离列表,对其进行排序,并寻找距离接近截止范围中心的点,但我认为这实际上可能比我正在做的要慢现在。

我也在尝试找出一些更智能的算法,因为这些点最初是按照它们定义轮廓的顺序存储的——我应该能够在列表中的每个点之前和之后消除一些点进行组合......但是,当我尝试使用 Python 的默认 for 循环使用这个事实来生成组合时,它最终比简单地使用 itertools 并生成所有内容要慢。

感谢任何建议。

谢谢!

【问题讨论】:

  • 您的问题非常广泛,您是否在图表中搜索?还是点云?
  • 这些点当前存储为一个 numpy 数组列表来表示坐标。列表的顺序是这样的,每个点都可以用一条线连接到下一个点,并让最终结果跟踪对象的轮廓,在这种情况下是一只手。我可以尝试从这些数据构建其他数据结构,但这可能太慢了。
  • 对我来说这听起来像一个图,图应该存储在树状结构中,这样你就可以做最近邻搜索之类的事情。例如,scipy numpy 有一个 KD-Tree,非常方便。
  • 你能扩展一下你真正想要完成的事情吗?据我现在了解,如果它们按顺序连接,则您有一个形成(手的)轮廓的点列表。现在您搜索彼此在一定距离范围内的 3 元素子集。为什么?目标是什么?由于可能的 3 元素子集的数量是 N 超过 3,这正在增长,因此显着加快速度的唯一希望是避免构建该组合列表,恕我直言。
  • 您似乎只考虑了第一个坐标分量之间的距离:B = points[1][0],换句话说,就是“x 分量”。 self.handContour.shape 是什么?我假设它是(60,2),但您的代码似乎另有说明。您是否只对检查 x 距离是否在界限内感兴趣?

标签: python algorithm opencv numpy


【解决方案1】:

我会首先计算所有点之间的成对距离,过滤掉那些符合您的规范(dist_min 和 dist_max),然后检查三个这样的节点的组合是否仍然符合标准(因为我只检查成对 - 一次,为了速度)。

import itertools
import numpy as np
from scipy.spatial.distance import pdist, squareform

points = np.random.rand(100,2)  # could be nodes in 3 dimensions too, but you specify a handpalm, so I'm guessing your contour is merely 2D

def palm_combinations(points, dist_min=.0, dist_max=.05):
    dists = pdist(points)
    # This matrix lists the distance between each pair of nodes 
    # (represented by their column and row index, so that the mat[i,j] 
    # represents the distance between points[i,:], points[j,:])
    mat = squareform(dists)  

    mask = (mat > dist_min) & (mat < dist_max)

    two_good_legs = {}  # store all combinations of point indices where "two legs" of the triangles have a distance that matches the spec.
    myinds = []
    for rowind, row in enumerate(mask):
        relevant = row[rowind+1:]  # distance to a point itself is always zero, hence exclude from list
        inds = np.where(relevant)[0] + (rowind+1)
        myinds.append(inds)
        two_good_legs[rowind] = list(itertools.combinations(inds, 2))

    triangles = []
    # The only thing left to do now is to check if the third leg's norm is also within spec.
    for k,v in two_good_legs.items():
        for tup in v:
            if tup[1] in myinds[tup[0]]:
                triangles.append((k, tup[0], tup[1]))
    return triangles

triangles 将列出满足您规格的点内的所有索引。如果您想返回实际坐标,只需获取points[triangles,:]。 您可以通过以下方式可视化所有这些:

import maptlotlib.pyplot as plt
plt.triplot(points[:,0], points[:,1], triangles)
plt.plot(points[:,0], points[:,1], 'ko ')

您的实现之间的时间差异(已修改以排除未知的 [0] 索引,请参阅我的评论)显示:

In [12]: %timeit  my_implementation(points, .1, .15)
1 loops, best of 3: 1.58 ms per loop

In [13]: %timeit your_implementation(points, .1, .15)
1 loops, best of 3: 2.32 s per loop

点的形状为(100,2),因此我的机器上的速度提高了大约 1470 倍。

如果你摆脱对squareform 的调用,你可以稍微提高速度,根据分析器,这是瓶颈,这不是绝对必要的,但它使代码更具可读性(“可读性很重要。 ”参见蒂姆·彼得斯 (Tim Peters) 的《Python 之禅》)。为此,您将进行以下更改:

def palm_combinations(points, dist_min=.0, dist_max=.05):
    dists = pdist(points)
    mask = (dists > dist_min) & (dists < dist_max)
    two_good_legs, myinds, triangles = {}, [], []
    s = points.shape[0]
    ind_u1, ind_un = 0, s - 1
    for rowind in xrange(s-1):
        relevant = mask[ind_u1:ind_un]
        ind_u1 = ind_un
        ind_un += s - 1*(rowind+2)
        inds = np.where(relevant)[0] + (rowind+1)
        myinds.append(inds)
        two_good_legs[rowind] = list(itertools.combinations(inds, 2))
    for k,v in two_good_legs.items():
        for tup in v:
            if tup[1] in myinds[tup[0]]:
                triangles.append((k, tup[0], tup[1]))
    return triangles

但是,对于小型数据集,速度提升不会很明显。

【讨论】:

  • 这似乎完美地完成了我所需要的。谢谢你。您能否看看我在上面发布的评论,看看是否有办法进一步改进这个算法?
【解决方案2】:

您可以使用 numpy.假设 comb 是您已经计算出的可能组合,您可以轻松地矢量化距离计算:

>>> import numpy as np
>>> comb = np.array(list(comb))
>>> dists = comb - np.roll(comb, -1)
# L2 norm
>>> dists = dists**2

dists 将是一个 Nx3 数组,分别包含 AB BC 和 CA 距离。

用你的条件掩盖它:

>>> mask = (dists > minDist) & (dists < maxDist)

查找所有距离都满足条件的行:

>>> rows = np.all(mask, axis=1)

返回满足条件的组合:

>>> comb[rows]

更新:刚刚注意到对于大 N 这仍然很慢。这是包含上述所有步骤的函数:

>>> def palm_combinations(points, min_dist=10, max_dist=100): 
        combs = np.array(list(itertools.combinations(points, 3)))
        dists = (combs - np.roll(combs, -1))**2
        mask = (dists > min_dist) & (dists < max_dist)
        return combs[np.all(mask, axis=1)]

对于100个点的样本数据:

>>> a = np.random.rand(100) * 500
>>> %timeit palm_combinations(a)
10 loops, best of 3: 79.5 ms per loop

函数的瓶颈是所有组合的生成:

>>> %timeit combs = np.array(list(itertools.combinations(a, 3)))
10 loops, best of 3: 69.2 ms per loop

更新 2:可以使用更复杂的方法来加速。使用np.fromiter:

# Define combinations data type (3 float each combination)
>>> dt = np.dtype('f,f,f')
# Fast numpy array conversion
>>> combs = np.fromiter(itertools.combinations(points, 3), dt)

函数类似于:

>>> def palm_combinations(points, min_dist=10, max_dist=100): 
        dt = np.dtype('f,f,f')
        combs = np.fromiter(itertools.combinations(points, 3), dt)
        combs = combs.view('f').reshape(-1,3)
        dists = (combs - np.roll(combs, -1))**2
        mask = (dists > min_dist) & (dists < max_dist)
        return combs[np.all(mask, axis=1)]

还有速度测试:

>>> %timeit palm_combinations(a)
10 loops, best of 3: 29.8 ms per loop

对于 N=100

【讨论】:

    【解决方案3】:

    如果轮廓点的数量非常多,您可能需要尝试启发式方法。 即取三个随机点,(检查最小和最大距离,)计算相应圆的半径,与之前计算的半径进行比较,重复。您必须考虑某种停止标准,例如最大迭代次数,或者在最后 x 次迭代中没有找到更好的半径,或者半径增长率低于 x%,或者这些的某种组合。

    除此之外,关于您在问题下的澄清评论: 你的术语或你的方法是错误的。 无法保证通过您的轮廓点的圆位于轮廓点的凸包内。例如,想象一只张开的手,该形状将具有凹形部分,如果所有三个点都在一个这样的部分内,则圆将位于手的外部。 我认为您的意思是内接在每个三点集的凸包内的圆。

    【讨论】:

    • 抱歉不清楚 - 这里的目标是生成满足基本距离标准的 3 个点的所有可能组合,找出所有这些点的圆圈,然后查看哪些圆圈位于通过检查中心的上方、下方、右侧和左侧的 4 个点是否在凸包内。问题是,我有很多潜在的圈子,这个过程很慢。
    • 好的,感谢您的澄清。但是,如果我理解正确,那么您将拥有一组位于凸包内的圆圈,最后一步是选择最大的一个。如果是这种情况(并且如果点数很大(N=100,您有 160.000 个三元组要检查;N=1000 有 1.6 亿个要检查),那么您仍然可以从启发式方法中受益,因为它应该是足以找到一个相当大的圆圈,不一定是最大的圆圈。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2019-03-31
    • 2023-01-30
    相关资源
    最近更新 更多