我如何获得由矩阵中超过 1 个其他黑色像素连接的黑色像素的数量(计数或总和)?
How would I get the number (the count or sum) of black pixels connected by more than 1 other black pixel in a matrix?
我正在尝试获取二进制矩阵中超过 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 是预期的结果。有办法吗?
您可以将 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
我正在尝试获取二进制矩阵中超过 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 是预期的结果。有办法吗?
您可以将 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