2

I have a raster layer in QGIS and I would like to write Python code to change it's max and min values that would normally be under Layer Properties> Symbology> Band Rendering. The layer has a Singleband gray render. This is what I've written so far:

rLayer = iface.activeLayer()

rLayer.renderer().setClassificationMin(-426)
rLayer.renderer().setClassificationMax(8848)

Sadly it doesn't work for Singleband gray renders, only for Singleband pseudocolor.

Could anyone tell me what changes I should make to the code to make it work for the grayscale (Singleband gray)?

1

1 Answer 1

3

To configure the minimum and maximum values of a single band gray symbol you must configure the QgsContrastEnhancement

Apply and modify the values of the following code to see the effect

capa=iface.activeLayer()
renderer=capa.renderer()
provider=capa.dataProvider()
GrayRenderer = QgsSingleBandGrayRenderer(provider,1) #create a new renderer
   

#If you don't need to create a renderer but modify the existing one, start # 
#here and at the end apply the contrastEnhancement

myType = renderer.dataType(1)
myEnhancement = QgsContrastEnhancement(myType)
contrast_enhancement = QgsContrastEnhancement.StretchToMinimumMaximum
myEnhancement.setContrastEnhancementAlgorithm(contrast_enhancement,True)
myEnhancement.setMinimumValue(20.3)   #Set the minimum value you want
myEnhancement.setMaximumValue(50.5)   #Put the maximum value you want 
capa.setRenderer(GrayRenderer)
capa.renderer().setContrastEnhancement(myEnhancement)
capa.triggerRepaint()

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.