Search code examples
rgaussiangaussianblur

Extract standard deviation and mean of pixel values within a radius using Gaussian filtering in R


I have a matrix like the following one, obtained from a raster file:

0   0   0   0   0   0   0   4   254 252
0   0   0   0   0   0   0   0   255 246
0   0   0   0   0   0   0   1   255 246
0   0   0   0   0   4   32  254 255 246
0   0   0   0   8   255 255 255 255 246
0   0   0   0   0   11 214 254 255 246
0   0   0   0   0   0   0   1   255 246
0   0   0   0   0   0   0   1   255 246
1   0   0   0   0   0   0   2   255 253
247 247 247 247 247 247 247 247 249 251

And I would like to use a Gaussian filter with a radiux "x" that is able to estimate standard deviation and mean of the considered pixel values within this radius. As output I would like to get a matrix for the "mean" (estimated for each pixel by using the filtering radius) and a matrix for the "standard deviation".

Do you have any suggestion on how to do it in R?


Solution

  • Given matrix m

    m <- matrix(c(0,0,0,0,0,0,0,4,254,252,0,0,0,0,0,0,0,0,255,246,0,0,0,0,0,0,0,1,255,246,0,0,0,0,0,4,32,254,255,246,0,0,0,0,8,255,255,255,255,246,0,0,0,0,0,11,214,254,255,246,0,0,0,0,0,0,0,1,255,246,0,0,0,0,0,0,0,1,255,246,1,0,0,0,0,0,0,2,255,253,247,247,247,247,247,247,247,247,249,251), ncol=10, byrow=TRUE)
    

    You can compute the (Gaussian) weighted mean like this

    library(raster)
    r <- raster(m)
    
    # Gaussian filter
    gf <- focalWeight(r, .2, "Gauss")
    rg <- focal(r, w=gf, na.rm=TRUE, pad=TRUE)
    
    # plot(rg)
    # as.matrix(rg)
    

    I don't know how you would compute a weighted standard deviation.

    For a standard focal mean and sd

     fm <- focal(r, w=matrix(1,3,3), fun=mean, pad=TRUE, na.rm=TRUE) 
     fd <- focal(r, w=matrix(1,3,3), fun=sd, pad=TRUE, na.rm=TRUE)