1

I need to do the raster calculator operation as "raster + constant" in Python. The input rasters are DEM data with float original type and -9999 for the NoData. The constant is float too.

In 1st way, I call the gdal_calc.py rutin:

command = 'gdal_calc.py -A {0} --outfile={1} --calc="A+{2}" \
       --NoDataValue=-9999 --type="Float32" --overwrite \
       --quiet'.format(filename, savename, median)
os.system(command)

In 2nd way, I open the file with gdal and directly operate the band values:

driver = gdal.GetDriverByName('GTIFF')
AD_file = gdal.Open(filename, gdal.GA_Update)
band=AD_file.GetRasterBand(1).ReadAsArray()
band = np.where([band > -9999], band + median, -9999) # raster calculator analog
AD_file.GetRasterBand(1).WriteArray(band[0,:,:])
AD_file=None

They both give the result. But... the results are different in therm of vales when I compare the min/max. For example, if the median=5 so the calculation is 'raster+5':

  • the source raster min/max: 241/642
  • the gdal_culc.py result min/max: 253/661
  • the 2nd way result min/max: 246/647

What happens with gdal_calc?!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.