loops - Efficient implementation of summed area table/integral image in R -


i trying construct summed area table or integral image given image matrix. of dont know is, wikipedia:

a summed area table (also known integral image) data structure , algorithm , efficiently generating sum of values in rectangular subset of grid

in other words, used sum values of rectangular region in image/matrix in constant time.

i trying implement in r. however, code seems take long run.

here pseudo code this link. in input matrix or image , intimg whats returned

 i=0 w    sum←0     j=0 h       sum ← sum + in[i, j]        if = 0          intimg[i, j] ← sum       else          intimg[i, j] ← intimg[i − 1, j] + sum       end if    end  end 

and here implementation

 w = ncol(im) h = nrow(im) intimg = c(na) length(intimg) = w*h  for(i in 1:w){ #x   sum = 0;   for(j in 1:h){ #y     ind = ((j-1)*w)+ (i-1) + 1 #index     sum = sum + im[ind]     if(i == 1){       intimg[ind] = sum     }else{       intimg[ind] = intimg[ind-1]+sum     }   } } intimg = matrix(intimg, h, w, byrow=t) 

example of input , output matrix:

enter image description here

however, on 480x640 matrix, takes ~ 4 seconds. in paper describe take on order of milliseconds dimensions.

am doing inefficient in loops or indexing?

i considered writing in c++ , wrapping in r, not familiar c++.

thank you

you try use apply (isn't faster for-loops if pre-allocating memory):

areatable <- function(x) {   return(apply(apply(x, 1, cumsum), 1, cumsum)) }  areatable(m) #      [,1] [,2] [,3] [,4] # [1,]    4    5    7    9 # [2,]    4    9   12   17 # [3,]    7   13   16   25 # [4,]    9   16   22   33 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -