如何将坐标获取到 R 中 apply() 调用的函数中?

问题描述 投票:0回答:1

我正在尝试编写自己的图像过滤函数,一种更简单的风格是对单元格邻居值进行平均。我有一个带有像素值的矩阵,但我没有使用巨大的 for 循环,而是尝试使用 apply,但似乎无法获取正在“处理”的单元格的当前坐标。

我正在努力让任何多变量函数诚实地与 apply() 一起使用,但理想情况下我认为我会将整个矩阵传递给函数?

picture = matrix(data=0,nrow=px,ncol=px)

# I then have a function that draws a few squares and adds some random noise
# Now I'd like to go through the matrix, find the cells neighbour values, avg.
 
test <- function(x,cur_matrix){
    up    = cur_matrix[i,j+1]
    left  = cur_matrix[i-1,j]
    right = cur_matrix[i+1,j]
    down  = cur_matrix[i,j-1]

    avg = ( up + down + left + right ) / 4
    x = avg
    return(x)
}

picture_2 = apply(picture, 1:2, test, cur_matrix = picture)

我怎样才能将矩阵“图片”和当前的 i,j 坐标传递到这个函数中?

r image matrix apply
1个回答
0
投票

你可以这样尝试

sapply

# dummy picture pixel matrix
set.seed(0)
pic <- matrix(runif(30), 5)

# complex coordinations
idx <- row(pic) + 1i * col(pic)

# average by neighboring pixels
pic_out <- `dim<-`(sapply(c(idx), \(p) {
  u <- idx[abs(p - idx) <= 1]
  mean(diag(pic[Re(u), Im(u)]))
}), dim(pic))

我们将会看到

> pic
          [,1]      [,2]       [,3]      [,4]      [,5]       [,6]
[1,] 0.8966972 0.2016819 0.06178627 0.7698414 0.7774452 0.26722067
[2,] 0.2655087 0.8983897 0.20597457 0.4976992 0.9347052 0.38611409
[3,] 0.3721239 0.9446753 0.17655675 0.7176185 0.2121425 0.01339033
[4,] 0.5728534 0.6607978 0.68702285 0.9919061 0.6516738 0.38238796
[5,] 0.9082078 0.6291140 0.38410372 0.3800352 0.1255551 0.86969085
> pic_out
          [,1]      [,2]      [,3]      [,4]      [,5]      [,6]
[1,] 0.4546293 0.5146388 0.3098210 0.5266930 0.6873031 0.4769267
[2,] 0.6081799 0.5032460 0.3680813 0.6251678 0.5616213 0.4003576
[3,] 0.5387903 0.6105087 0.5463696 0.5191846 0.5059061 0.2485087
[4,] 0.6284957 0.6988927 0.5800774 0.6856513 0.4727331 0.4792857
[5,] 0.7033917 0.6455558 0.5200689 0.4704000 0.5067387 0.4592113
© www.soinside.com 2019 - 2024. All rights reserved.