【问题标题】:How to optimize for-loop如何优化for循环
【发布时间】:2019-02-10 18:26:30
【问题描述】:

我正在使用 for 循环过滤来自 opencv knnFlann 匹配器的匹配项,但我需要对其进行优化

代码:

def orb_calc_matches(matches, distance_range=0.65):
    good_matches = []
    queried_matches = []

    for i in range(len(matches)):
        if len(matches[i]) == 2:
            if ((matches[i][0].trainIdx not in queried_matches) and (matches[i][0].distance < distance_range * matches[i][1].distance)):
                good_matches.append(matches[i][0])
                queried_matches.append(matches[i][0].trainIdx)
    return good_matches

有人可以提出一些更有效的方法吗?

【问题讨论】:

标签: python performance for-loop optimization


【解决方案1】:

将queried_matches 设为set。并使用for m in matches: 而不是索引循环,因为不需要索引。

def orb_calc_matches(matches, distance_range=0.65):
    good_matches = []
    queried_matches = set()

    for m in matches:
        if len(m) == 2:
            if ((m[0].trainIdx not in queried_matches) and
                (m[0].distance < distance_range * m[1].distance)):
                good_matches.append(m[0])
                queried_matches.add(m[0].trainIdx)
    return good_matches

【讨论】:

  • 它可以工作,而且速度有点快,但差别不大。我的整个脚本从 18.65 到 18,22sek 变得更快,你认为使用 concurrent.futures.ThreadPoolExecutor 搜索会是一件好事吗?平行?
  • 我会考虑在它到达这个函数之前减少匹配的数量。对匹配进行排序或在[0].trainIdx 上排序匹配可能会更快,然后queried_matches 将只是一个索引,而测试将是m[0].trainIdx &gt; queried_matches。
猜你喜欢
  • 2011-06-15
  • 2022-11-03
  • 2010-11-15
  • 2011-08-30
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
相关资源
最近更新 更多