Recursive algorithm or flood filling algorithm for raster?

218 views Asked by At

I've got a binary raster like this:

101101
010111
101011
111101

Now I need to do this row by row: Go through row and count the adjacent cells which are 1 (only the cells in the row!). And I would like to get a vector or something like this. for example for the raster above it would be:

1st row: 1 2 1

2nd row: 1 3

3rd row: 1 1 2

4th row: 4 1

I read a lot about flood filling algorithm and so on. But I just don't get it right.

I tried this recursive algorithm:

rec=function(x)
   {if (x==0)
       {return 0)
    else return(1+rec(x+1))}

But it's not working.

2

There are 2 answers

0
Roman Luštrik On

You could try using rle.

xy <- read.table(text = "1 0 1 1 0 1
0 1 0 1 1 1
1 0 1 0 1 1
1 1 1 1 0 1", sep = "")
xy

apply(xy, MARGIN = 1, FUN = function(x) {
  x <- rle(x)
  x$lengths[x$values == 1]
})

[[1]]
V2 V5    
 1  2  1 

[[2]]
V3    
 1  3 

[[3]]
V2 V4    
 1  1  2 

[[4]]
V5    
 4  1
2
MBo On

You don't need flood filling algorithm at all. Recursion is not needed too.

Just count non-zeros. Simplest state machine:

Starting state in the beginning of every line is 0
When state is 0 and you meet 1, remember X-position Start and make state 1
When state is 1 and you meet 0, make state 0 and add `Current - Start` to list
In other cases do nothing