3

I have a fairly complex Python program that needs to use a single command of GDAL. Currently I'm using os.popen to call the command gdalwarp from Python. This works, but is an ugly approach, so I'd prefer to use GDAL from within the Python program. However I'm a bit overwhelmed by the documentation and I have found no simple example I can use to tackle my problem.

The command I'm using is something like:

gdalwarp -overwrite -co compress=none -of Gtiff -t_srs EPSG:4326 -te -180.02250000 -90.02250000 179.97750000 90.02250000 -tr 0.045 0.045 *.tiff output.tiff

How can I reproduce the behaviour of this command with Python calls to the GDAL library?

1

1 Answer 1

6

You can first convert all tif input as a single vrt, then run the gdal.Warp

from pathlib import Path
from osgeo import gdal

vrt_name= 'input.vrt'
tifs = [str(p) for p in Path('.').glob('*.tiff')]
my_vrt = gdal.BuildVRT(vrt_name, tifs)
my_vrt = None

ds_input = gdal.OpenEx(vrt_name, gdal.OF_RASTER)
ds = gdal.Warp('output.tif', ds_input, options="-overwrite -co compress=none -of Gtiff -t_srs EPSG:4326 -te -180.02250000 -90.02250000 179.97750000 90.02250000 -tr 0.045 0.045")
del ds
del ds_input

You can have 4 syntax for options (3rd and more args). The way to provide options is similar to Issue to convert from PostgreSQL input to GPKG using Python GDAL API function gdal.VectorTranslate except you need to provide a gdal.WarpOptions

2
  • Thanks, this is what I was looking for. Just a minor comment. My call to gdal.BuildVRT did not produce any output file. Instead, I was able to use the my_vrt object instead of 'input.vrt'. I'm not sure if this is how it is supposed to work, but it does the job and is a cleaner solution, as it does not write temporary files in disk.
    – Pythonist
    Commented May 31, 2021 at 17:31
  • Intrigued by your last paragraph, I'm now trying to use a dictionary instead of a long string to setup warp. Unfortunately I can't find the way to do it. I posted a new question here in case you want to follow up. gis.stackexchange.com/questions/398223/…
    – Pythonist
    Commented May 31, 2021 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.