Search code examples
rmaxaggregatepixelraster

Calculate the maximum value for a group of pixels


I have a raster image with a resolution of 1,1.

I want to decrease the resolution to 4,4 but still have the maximum value of the pixel that makes up the new 4,4 pixel.

I can reduce the resolution by using:

chm4 <- aggregate(chm, 4)

However, this gives you the average maximum from each pixel that makes up this new pixel.

I tried to convert the raster to a matrix so it takes the form of:

     [,1]  [,2] [,3] [,4] [,5] [,6] [,7] [,8]...
[1,]  63    34   45   76   21   54   35   45
[2,]  77    54   43   34   12   23   73   26
[3,]  56    73   26   27   81   29   34   52
[4,]  31    48   61   35   76   38   17   87
[5,]  16    24   71   45   58   60   14   35
[6,]  28    64   27   63   18   62   43   27
[7,]  27    48   76   27   54   61   52   44
[8,]  56    37   53   62   37   47   52   38 
...

Is there a way to calculate the max of all values within, for example, rows 1 to 4 and columns 1 to 4?

This would also need to be applied across the whole matrix which has 1000's of rows and columns back into a matrix form to look like:

    [,1][,2]...
[1,] 77  87
[2,] 76  62
...

Solution

  • Here is another possibility, using a for-loop on a sample matrix (mat):

    x <- sample(1:100, 100, replace = TRUE)
    mat <- matrix(x, nrow = 10)
    mat2 <- matrix(nrow = nrow(mat)/4, ncol = ncol(mat)/4)
    
    for(i in 1:dim(mat2)[1]) {
      for(j in 1:dim(mat2)[2]) {
        row <- 4 * (i - 1) + 1
        col <- 4 * (j - 1) + 1
        mat2[i,j] <- max(mat[row:(row + 3), col:(col + 3)])
      }
    }