03 Dec

Use gdal_calc to calculate index (NDVI, NDWI, …) , add stats with gdalinfo and overview with gdaladdo

His GISguys!

Here is a simple example of how to use the very fast multi-thred gdal_calc to get NDWI with stats, histogram and overviews.

file='my_input_file.tif'
outfile='my_output_file.tif'
 
  system(
    paste('gdal_calc.py',
          '-A',file,
          '--A_band=2',
          '-B',file,
          '--B_band=4',
          paste(' --outfile=', outpufile,sep=''),
          paste(' --calc=','\"','(A.astype(float)-B)/(A.astype(float)+B)','\"',sep=''),
          paste('--type=','\'','Float32','\'',sep=''),
          paste('--co=','\"','COMPRESS=LZW','\"',sep='')))
 
  system(paste('gdalinfo -hist -stats',outpufile))
 
  system(
    paste('gdaladdo',
          outpufile,
          '2 4 8 16')

Here is another version with byte file as output (values ranging from 0 to 255, faster and smaller files):

file='my_input_file.tif'
outfile='my_output_file.tif'
 
  system(
    paste('gdal_calc.py',
          '-A',file,
          '--A_band=2',
          '-B',file,
          '--B_band=4',
          paste(' --outfile=', outpufile,sep=''),
          paste(' --calc=','\"','((((A.astype(float)-B)/(A.astype(float)+B))+1)*128)','\"',sep=''),
          paste('--type=','\'','Byte','\'',sep=''),
          paste('--co=','\"','COMPRESS=LZW','\"',sep='')))
 
  system(paste('gdalinfo -hist -stats',outpufile))
 
  system(
    paste('gdaladdo',
          outpufile,
          '2 4 8 16')

3 thoughts on “Use gdal_calc to calculate index (NDVI, NDWI, …) , add stats with gdalinfo and overview with gdaladdo

  1. Can please help me in calculating ndvi using C language. I need to work with multiple TIF file. I have single band in single TIF. Thanks in advance

  2. Hi, Congratulations on the site
    I want to do the ndvi through gdal, how can I use and execute the command that you put in this post?
    Thank you in advance for the answer

Leave a Reply

Your email address will not be published. Required fields are marked *