Python 用Numpy计算有效的总面积表
我试图使用python和numpy计算一个特性计数矩阵的值。目前我正在使用以下代码:Python 用Numpy计算有效的总面积表,python,arrays,optimization,numpy,Python,Arrays,Optimization,Numpy,我试图使用python和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):
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循环,但我不知道如何避免它们。有一个NumPy函数
cumsum
用于累计和。应用它两次将生成所需的表:
将numpy导入为np
A=np.random.randint(0,10,(3,4))
打印
打印A.cumsum(轴=0)。cumsum(轴=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]]
0.15 sec elapsed
性能分析:()
输出:
[[7 4 7 2]
[6 9 9 5]
[6 6 7 6]]
[[ 7 11 18 20]
[13 26 42 49]
[19 38 61 74]]
0.15 sec elapsed