【问题标题】:Efficient summed Area Table Calculation with Numpy使用 Numpy 进行有效的总面积表计算
【发布时间】:2014-10-22 20:34:30
【问题描述】:

我正在尝试使用 python 和 numpy 计算特征计数矩阵的summed area table。目前我正在使用以下代码:

def summed_area_table(img):

    table = np.zeros_like(img).astype(int)

    for row in range(img.shape[0]):
        for col in range(img.shape[1]):

            if (row > 0) and (col > 0):
                table[row, col] = (img[row, col] +
                                   table[row, col - 1] +
                                   table[row - 1, col] -
                                   table[row - 1, col - 1])
            elif row > 0:   
                table[row, col] = img[row, col] + table[row - 1, col]
            elif col > 0:
                table[row, col] = img[row, col] + table[row, col - 1]
            else:
                table[row, col] = img[row, col]

    return table

上面的代码对一个 3200 x 1400 的数组执行计算大约需要 35 秒。有没有办法使用 Numpy 技巧来加快计算速度?我意识到根本的速度问题在于嵌套的 python 循环,但我不知道如何避免它们。

【问题讨论】:

    标签: python arrays optimization numpy


    【解决方案1】:

    有一个 NumPy 函数 cumsum 用于累积和。应用它两次会产生所需的表:

    import numpy as np
    
    A = np.random.randint(0, 10, (3, 4))
    
    print A
    print A.cumsum(axis=0).cumsum(axis=1)
    

    输出:

    [[7 4 7 2]
     [6 9 9 5]
     [6 6 7 6]]
    [[ 7 11 18 20]
     [13 26 42 49]
     [19 38 61 74]]
    

    性能分析: (https://stackoverflow.com/a/25351344/3419103)

    import numpy as np
    import time
    
    A = np.random.randint(0, 10, (3200, 1400))
    
    t = time.time()
    S = A.cumsum(axis=0).cumsum(axis=1)
    print np.round_(time.time() - t, 3), 'sec elapsed'
    

    输出:

    0.15 sec elapsed
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 2014-06-14
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      相关资源
      最近更新 更多