I am trying to build a table of the total area or the whole image taking into account the image matrix. For those of you who donβt know what it is, from Wikipedia:
The summarized regions table (also known as the integrated image) is a data structure and algorithm for quickly and efficiently generating the sum of values ββin a rectangular grid subset
In other words, it is used to sum the values ββof any rectangular region in the image / matrix in constant time.
I am trying to implement this in R. However, my code seems to work too long.
Here is the pseudocode from this link . in is the input matrix or image, and intImg is what returned
for i = 0 to w do
sum β 0
for j = 0 to h do
sum β sum + in [i, j]
if i = 0 then
intImg [i, j] β sum
else
intImg [i, j] β intImg [i - 1, j] + sum
end if
end for
end for
And here is my 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 input and output matrix:

However, on a 480x640 matrix, this takes ~ 4 seconds. In the document, they describe it for the order of milliseconds for these measurements.
Am I doing something inefficient in my loops or indexing?
I thought about writing it in C ++ and wrapping it in R, but I'm not very familiar with C ++.
thanks