阅读矩阵数字&提取R中的特征

时间:2017-10-02 14:16:35

标签: r matrix

我有数字矩阵......让我们说它来自一张16 x 16像素的图片

Mat <- matrix(rbinom(16 * 16, 1, 0.5), ncol = 16, nrow = 16)

每次看当前像素周围的3x3像素内核并从中提取特征时,我希望每次大步移动1个像素。例如,我可能会查看给定像素并提取其周围3x3区域中存在多少个1或0。我可能会存储这些信息,然后移动到下一个像素等等。

我不确定如何:

从左到右跨越,逐行检查每次3x3区域。

允许最边缘的像素,因为它们没有3x3区域,在CNN中我相信这是零填充处理,但我不想算0,它们应该是NA等。

See image below

这显然是在某种循环中完成的 - 我不确定如何在R中编写代码。

1 个答案:

答案 0 :(得分:0)

# Stride 1 pixel at at time each time looking at a 3x3 pixel kernel around the current pixel 

for(c in 1:ncol(Mat)){
  for(r in 1:nrow(Mat)){
    if(r+2 < nrow(Mat) & c+2 < ncol(Mat)){
      print("Here's the current 3x3:")  
      print(Mat[r:(r+2),c:(c+2)])
      print("You can do your feature engineering step here.")
    }
    else if(r+2 < nrow(Mat) & !(c+2 < ncol(Mat))){
      print("You could pad as you described but based on the rest of your 
            description the result would be the same as just ommitting the padded
            cells.")
      cc <- ncol(Mat)
      print("Here's the current pseudo-3x3:")  
      print(Mat[r:(r+2),c:cc])

    }
    else if(!(r+2 < nrow(Mat)) & (c+2 < ncol(Mat))){
      rr <- nrow(Mat)
      print("Here's the current pseudo-3x3:")  
      print(Mat[r:rr,c:(c+2)])
    }
    else if(!(r+2 < nrow(Mat)) & !(c+2 < ncol(Mat))){
      c <- ncol(Mat)
      r <- nrow(Mat)
      print("Here's the current pseudo-3x3:")  
      print(Mat[r:rr,c:cc])
    }

  }
}