【发布时间】: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