QGis Normalize All Layers

I frequently load large numbers of layers into QGis. They all get normalized independently, which makes it difficult to compare them. So here's a chunk of Python code which normalizes them all together.

def GetAllLayersMinMax():
  minval = float('Inf')
  maxval = -float('Inf')
  for l in iface.legendInterface().layers():
    stats = l.dataProvider() \
                 .bandStatistics(
                    l.renderer().usesBands()[0], 
                    QgsRasterBandStats.All, 
                    l.extent(), 
                    0)
    minval = min(minval,stats.minimumValue)
    maxval = max(maxval,stats.maximumValue)
  return (minval,maxval)

def NormAllLayerColours(minval,maxval):
  for l in iface.legendInterface().layers():
    myType               = l.renderer().dataType(l.renderer().usesBands()[0])
    myEnhancement        = QgsContrastEnhancement(myType)
    contrast_enhancement = QgsContrastEnhancement.StretchToMinimumMaximum
    myEnhancement.setContrastEnhancementAlgorithm(contrast_enhancement,True)
    myEnhancement.setMinimumValue(minval)
    myEnhancement.setMaximumValue(maxval)
    l.renderer().setContrastEnhancement(myEnhancement)
    l.triggerRepaint()

#Use this
NormAllLayerColours(*GetAllLayersMinMax())

#Or this
NormAllLayerColours(1,1000)

links