QGIS – Guide to Using gdal_translate and -scale

gdal-translateqgisscale

I am working on normalizing some rasters so that data taken on different days and calibrations can be seen in the the same relative view.

in gdal_translate the -scale option looks like this:

-scale [src_min src_max [dst_min dst_max]]:

so if I use the format

-scale src_min src_max 0 1

I get the result I am looking for now.
However I would like to use the option to not provide the src values and just use the input.

I am wondering if anyone could help me with the proper syntax for this, or if my best option is to just read out the src values before and then apply them in the script.

Best Answer

Thanks for all of the suggestions and help. The scale normalization is very useful when doing code, however in my case the original idea of putting the minimum and maximum in code looks like the only solution at this point.

I did not find a solution for doing it at the command line.

Here is a code snippet from the working solution: (Note that originally I was writing nodata to 0 as well, and this method breaks the nodata transformation. In my code I had to re-run the translate with nodata set to 0 as the only transformation to get it to finish the whole task!)

from qgis.core import *
from qgis.utils import *
from qgis.gui import *

import processing
from PyQt4.QtCore import *


#define functions

def loadraster(cur_raster):
    fileInfo = QFileInfo(cur_raster)
    baseName = fileInfo.baseName()
    rlayer = QgsRasterLayer(cur_raster, baseName)
    if not rlayer.isValid():
      print "Layer failed to load!"
    return rlayer


proj = QgsProject.instance()
proj.clear()

infile = "C:/QGISwork/ving_script/mergetest.tif"
outfile = "C:/QGISwork/ving_script/mergetest_out.tif"

#load raster file
mlayer = loadraster(infile)
#this part gets the extent from the original file 

ext = mlayer.extent()
extrep = ','.join([unicode(ext.xMinimum()), unicode(ext.xMaximum()), unicode(ext.yMinimum()), unicode(ext.yMaximum())]) 

#now get the stats whcih contain min and max values
renderer = mlayer.renderer()
provider = mlayer.dataProvider()
extent = mlayer.extent()
stats = provider.bandStatistics(1, QgsRasterBandStats.All,extent, 0)

print stats.minimumValue
print stats.maximumValue

#we don't need the layer any more so clear memory
QgsMapLayerRegistry.instance().removeMapLayer(mlayer.id())

#Run the algorithm with all of the inputs:
processing.runalg('gdalogr:translate', infile, 100, True, "0", 0, "", extrep , False,  5, 4, 75, 6, 1, False, 3, False, "-scale "+str(stats.minimumValue)+" "+str(stats.maximumValue)+" "+"0 1", outfile)