Search code examples
gdal

How to downscale a raster layer with GDAL resampling to 95th percentile?


How can we calculate the 95th percentile for each raster cell of a downsampled raster?

Lets say we have a high resolution raster layer (1m digital surface model) and want to create a version of it with lower resolution (50m surface model). Instead of standard metrics such as median we want to assign the new raster cells with the 95th percentile of the underlaying values.

With e.g. gdalwarp -tr 50 50 -r med dsm_1m.tif dsm_50m_percentile.tif we could calculate the median version. And gdalwarp supports further resampling methods such as q1 or q3 for the first and third quartile, but no option to define custom values.


Solution

  • gdal seems not to support this out of the box.

    Alternatives are e.g.:

    with GRASS Gis r.resamp.stats

    grass7:r.resamp.stats --input='dsm_1m.tif' --method=11 --quantile=0.95 --output='dsm_50m_percentile.tif' --GRASS_REGION_CELLSIZE_PARAMETER=50
    

    with R terra::aggregate()

    library(terra)
    
    input <- "dsm_1m.tif"
    output <- "dsm_50m_percentile.tif"
    
    f = function(v){
      quantile(v, .95, type = 1, na.rm=TRUE)
    }
    
    aggregate(r, fact=50, fun=f, filename = output)