2014-08-28 2 views
2

저는 python과 numpy를 사용하여 특징 수 행렬의 summed area table을 계산하려고합니다. 현재 I는 다음과 같은 코드가 사용하고Numpy로 효율적인 합계 면적 계산

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 트릭을 사용하여 계산 속도를 높이는 방법이 있습니까? 근본적인 속도 문제가 중첩 된 파이썬 루프에 있다는 것을 알았지 만이를 피하는 방법을 모른다.

답변

5

누적 합계에 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