 PaulBeales - 2 years ago 125
R Question

Reading Matrix numbers & extracting features in R

I have matrix of numbers...let's say it came from a picture with 16 x 16 pixels

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

I'd like to stride 1 pixel at at time each time looking at a 3x3 pixel kernel around the current pixel and extract features from that. For example I might look at a given pixel and extract how many 1's or 0's are present in the 3x3 area around it. I might store this information then move along to the next pixel etc etc.

I'm unsure how to:

Stride across from left to right, row by row checking the 3x3 region each time.

and

Allowing for the pixels at the very edge as they won't have a 3x3 region, in CNNs I believe this is handle by zero padding, but I don't want to count 0's they should probably be NAs etc. This is obviously done in a loop of some kind - i'm unsure how to code this in R. Hack-R
# 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])
}

}
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download