Q:

How to resample a raster layer to match a specific raster layer's cell size?

I would like to resample the cell size of a GeoTIFF raster layer with dimensions equal to the reference file (a Sentinel-2 B12 band with 20 m resolution to 10 m resolution).
I use the following code but doesn't work because the new raster created remains the same with 20 m resolution of cell size. Can someone help me with this?

A:

You can use gdalwarp to achieve this.
from osgeo import gdal

# open reference file and get resolution
referenceFile = "Path to reference file"
reference = gdal.Open(referenceFile, 0)  # this opens the file in only reading mode
referenceTrans = reference.GetGeoTransform()
x_res = referenceTrans[1]
y_res = -referenceTrans[5]  # make sure this value is positive

# specify input and output filenames
inputFile = "Path to input file"
outputFile = "Path to output file"

# call gdal Warp
kwargs = {"format": "GTiff", "xRes": x_res, "yRes": y_res}
ds = gdal.Warp(outputFile, inputFile, **kwargs)

Note that gdal.Warp() is just a Python wrapper for gdalwarp (which is a command line utility) so you can pass the same arguments you would pass to a gdalwarp call. The only thing to keep in mind is that the argument names might be a little bit different but you can check the equivalent names in the documentation. You can control other things such as the source and target spatial reference as well as the resampling algorithm used.

