0
\$\begingroup\$

I have a 3-D array in numpy, of dimensions 3000 x 2000 x 8

I need to modify the cells of the array so that each cell will contain the sum of all cells above and left of it, inclusive the current cell.

I am doing it using loops like below, but it is taking around 5 minutes to complete the program run. Is there a faster way in Python to achieve this (preferably without a loop)?

for depth in range(simg.shape[2]):
    for row in range(1,simg.shape[0]-1):
        for col in range(1,simg.shape[1]-1):
            simg[row,col,depth]=simg[row-1,col,depth]+simg[row,col-1,depth]+simg[row,col,depth]-simg[row-1,col-1,depth]
\$\endgroup\$
2
  • 1
    \$\begingroup\$ You should provide code which is ready to be executed if we copy/paste to our IDE. How can we help you if you don't help us ? \$\endgroup\$ Commented Jul 14, 2021 at 8:21
  • \$\begingroup\$ Seems like you want a convolution with a custom kernel. numpy and scipy offer fast implementation of such functions. Try searching about convolution or 2d convolution. Seems like you want a 3x3 kernel like [[0,1,0],[1,1,0],[0,0,0]] \$\endgroup\$
    – xuma202
    Commented Jul 14, 2021 at 15:12

1 Answer 1

0
\$\begingroup\$

I used integral function from openCV. It worked fast (within a second)!

iimg=cv.integral(simg)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.