Search code examples
pythonrastergdalresample

How to use gdal.Wrap() to resample a raster with nan cell


I used gdal.Wrap() to resample from a high resolution to a lower. However, my raster has no value (nan). So, when I set resampleAlg, the larger grids with nan(s) will become nan.

Here is my reprex in Python:

from osgeo import gdal

### resample and reproject
### data are from MOD11A2 and MYD11A2, and have been converted into annual mean values
raster_rprj = gdal.Warp("./2015_daytime_mean_re.tif",
                        "./2015_daytime_mean_clip2.tif", dstSRS = "EPSG:4326",
                        xRes = 0.008, yRes = 0.008, resampleAlg = "average")

raster_rprj = None

I hope it runs as the function np.nanmean()

Raster data is here.


Solution

  • Before the resample, you could replace NaN values with averages.

    The numpy expression to achieve that is the following:

    numpy.nan_to_num(A,nan=numpy.nanmean(A))
    

    Where A is the numpy array of your pixels.

    You run it like this:

    gdal_calc.py -A 2015_daytime_mean_clip2.tif \
    --calc="numpy.nan_to_num(A,nan=numpy.nanmean(A))" \
    --outfile=2015_daytime_mean_nan_to_num.tif
    

    More about GDAL Calc: https://gdal.org/programs/gdal_calc.html

    Then you can run the resample.