0

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.

Muhammad Faizan Uddin
  • 1,339
  • 12
  • 29
Cocilein
  • 45
  • 5

2 Answers2

0

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
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
0

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
MBo
  • 77,366
  • 5
  • 53
  • 86
  • ok thank you very much for your answer! I tried that and it worked for a small raster. But I have to deal with large rasters (180x480) and it just takes too much time. Maybe my version is just not efficient enough. – Cocilein Dec 16 '16 at 13:44
  • This algorithm has the best possible run time - it visits every raster element only once. It should be blazing fast for any reasonable raster size. – MBo Dec 16 '16 at 13:57