0

我正在尝试获取由二进制矩阵中超过 1 个其他黑色像素连接的 1(黑色像素)的数量。我有一个矩阵...

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

它输出一个矩阵...

      [,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

我现在正试图弄清楚如何使用这个矩阵来获取连接了超过 1 个其他黑色像素的所有黑色像素的计数(总和),例如......

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

我认为 8 是预期的结果。有没有办法做到这一点?

4

1 回答 1

2

您可以diff与 结合使用apply以获得具有 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

数据:

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
于 2019-10-14T14:52:52.670 回答