I have a list of binary matrices. In each matrix, I want to detect regions of white pixels (0
) surrounded by ring (a chain) of connected black pixels (1
).
For example, in the matrix below, there are two regions of white pixels (zeros) both entirely surrounded by a "chain" of connected 1s: the 2x2 and the 3x2 group of 0s.
m
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 1 1 1 1 0 0 1
# -> [2,] 1 0 0 1 1 1 1
# -> [3,] 1 0 0 1 0 0 1 <-
# [4,] 1 1 1 1 0 0 1 <-
# [5,] 1 0 0 1 0 0 1 <-
# [6,] 0 1 1 1 1 1 1
m <- matrix(c(1, 1, 1, 1, 0, 0, 1,
1, 0, 0, 1, 1, 1, 1,
1, 0, 0, 1, 0, 0, 1,
1, 1, 1, 1, 0, 0, 1,
1, 0, 0, 1, 0, 0, 1,
0, 1, 1, 1, 1, 1, 1),
byrow = TRUE, nrow = 6)
An example with three binary matrices in a list
:
set.seed(12345)
x <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)
set.seed(9999)
y <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)
set.seed(12345)
z <- matrix(sample(c(0,1), 225, prob=c(0.8,0.2), replace=TRUE), nrow = 15)
mat_list <- list(x, y, z)
I have thought of using the boundaries
function in the raster
package, so I start by converting the matrices to raster:
library(igraph)
library(raster)
lapply(list, function (list) {
Rastermat <- raster(list)
})
Any guidance on how I could implement this would be appreciated.