I am trying to get the number of 1s (black pixels) connected by more than 1 other black pixel in a binary matrix. I have a matrix...

set.seed(1234)
mat <- matrix(rbinom(30, 1, 0.5), nrow = 5)

which outputs a matrix...

      [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    1    1    0    0    0
[2,]    1    1    1    1    0    0
[3,]    1    0    1    0    0    0
[4,]    1    0    1    1    0    0

I am now trying to figure out how to use this matrix to get the count (sum) of all black pixels that have more than 1 other black pixel connected such as...

[1,2] [1,3] [2,1] [2,2] [2,3] [3,1] [3,3] [4,3] = 8 

Where 8 I would think would be the expected result. Is there a way to do this?

1

There are 1 best solutions below

7
On BEST ANSWER

You can use diff in combination with apply to get the number of neighbour pixels having a 1.

f  <- function(x) {
  tt  <- diff(x)==0  #See it there is no difference between Neighbors - Length is 1 less then x
  (c(0, tt) + c(tt, 0)) * x #Add a Zero at the begin and end and multiply it with x to get the number of Neighbors in 1 direction
}

n  <- t(apply(mat, 1, f)) + apply(mat, 2, f) #Use function f over rows and cols to get the number of Neighbors is two directions

sum(n>1)
#[1] 8

which(n>1, arr.ind = T)
     row col
#[1,]   3   1
#[2,]   4   1
#[3,]   5   1
#[4,]   4   2
#[5,]   5   2
#[6,]   1   3
#[7,]   2   6
#[8,]   3   6

n
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    0    1    3    1    0    1
#[2,]    1    0    1    0    0    2
#[3,]    2    0    0    0    0    2
#[4,]    3    3    1    0    0    1
#[5,]    2    2    0    0    0    0

Data:

set.seed(1234)
mat <- matrix(rbinom(30, 1, 0.5), nrow = 5)
mat
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    0    1    1    1    0    1
#[2,]    1    0    1    0    0    1
#[3,]    1    0    0    0    0    1
#[4,]    1    1    1    0    0    1
#[5,]    1    1    0    0    0    0