2

Is it possible to insert a python variable into gdal_calc expression?

For example:

mean = [stats[2]] ##mean value
gdal_calc.py -A Input.tif --outfile=Output.tif --calc="1*(A>=mean)" --NoDataValue=0 --type='Byte'
1
  • 1
    Not tested but maybe something like: --calc="1*(A>={value})".format(value = mean)
    – Joseph
    Jan 15, 2018 at 13:31

1 Answer 1

2

Sure thing. Since gdal_calc is a python module, you could even import it directly and use as any other module, but it's not really built with that in mind, it's easier to just use it as an utility.

To call a process from terminal/cmd within python, use os.system:

import os

gdal_path = 'whatever/path/gdal/is/installed/at'
gdal_calc_path = os.path.join(gdal_path, 'gdal_calc.py')

# Arguements.
input_file_path = 'input/file/path/file.tif'
output_file_path = 'output/file/path/file.tif'
calc_expr = '"1 * (A >= mean)"'
nodata = '0'
typeof = '"Byte"'

# Generate string of process.
gdal_calc_str = 'python {0} -A {1} --outfile={2} --calc={3} --NoDataValue={4} --type={5}'
gdal_calc_process = gdal_calc_str.format(gdal_calc_path, input_file_path, 
    output_file_path, calc_expr, nodata, typeof)

# Call process.
os.system(gdal_calc_process)
3
  • 1
    note: for new python code, you should use the subprocess module, not os.system: docs.python.org/3/library/… so it would be subprocess.run(gdal_calc_process, shell=True) Mar 20, 2020 at 18:22
  • 1
    @roberto-ribeiro Hi, can you please explain the term nodata = '0', i.e., why an integer value needs to be quoted? I'm experimenting with it but this seems to have no effect on my output, perhaps I'm missing something. Thank you
    – PDash
    Aug 20, 2020 at 7:27
  • 1
    @PDash It's because you are constructing a string there, which is what os.system uses to run a process. If it's not working, you can construct the gdal_calc call by hand at a text file and try calling it directly from cmd/terminal so you can inspect the error messages. Aug 22, 2020 at 11:19

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.