我想要计算一个只有一个黑色像素邻域的18x18矩阵中黑色像素的数目。邻域包括像素的N,NE,E,SE,S,SW,W,NW。
到目前为止我有:
neigh_1_function <-函数(矩阵){.}
没什么,请帮帮我:
发布于 2022-03-01 23:41:35
(我希望我不是在帮你做作业.)
这被称为摩尔邻里,以防万一,帮助找到信息。下面的解决方案并不是超级高效的;如果您需要对大量迭代或大得多的矩阵执行此操作,您可能应该像在C++中那样查找一些这篇博客文章代码(尽管它实现了环绕矩阵边缘的循环邻域)。我有一些更理想/更有效的方法,利用稀疏矩阵乘法文档这里 (PDF格式;效用函数)。
我认为下面的代码可以工作,但我还没有对它进行太多的测试。最好在一个易于手工测试的小矩阵上试一试:
## matrix of relative row/col positions of neighbours
nbr_mat <- as.matrix(expand.grid(c(-1,0,1), c(-1,0,1)))
nbr_mat <- nbr_mat[-5,] ## don't count self
## return number of neighbours of matrix element (i,j)
pixel_nbrs <- function(i,j) {
## compute absolute row/col positions of nbrs
nbr_ind <- sweep(nbr_mat, MARGIN = 1, STAT = c(i,j), FUN = "+")
## identify rows corresponding to positions within matrix bounds\
## (refers to *global* N value)
in_bounds <- apply(nbr_ind <= N & nbr_ind >= 1, 1, all)
## extract values (refers to *global* M)
pix_vals <- M[nbr_ind[in_bounds,]]
## count number of nbrs
return(sum(pix_vals))
}
## vectorize so we can run it for multiple {i,j}
vpix <- Vectorize(pixel_nbrs)模拟示例:
set.seed(101)
N <- 18
M <- matrix(sample(0:1, 18^2, replace= TRUE), 18, 18)表格:
## apply counting function for all combinations of row/col inds
nbrs <- outer(1:N,1:N, vpix)
## count number with exactly 1 nbr
sum(nbrs == 1)https://stackoverflow.com/questions/71315633
复制相似问题