My problem is to implement a custom contrast enhancement for the raster images. Its not a linear enhancement, it is based on a logarithmic function.

I thought I can update the renderer block like we can do for the data provider. But it seems the writeBlock is available only for the data provider.

layer = iface.activeLayer()
rdp = layer.dataProvider()
block = rdb.block(1,extent, cols, rows)

This block gives the actual values from the raster. Not the ones from the renderer.

How do I write a function for custom Enhancement?


For implementing a custom contrast enhancement for raster images you need to define several things. Assuming you have a raster with a QgsSingleBandPseudoColorRenderer and you want a QgsSingleBandPseudoColorRenderer, to implement a custom contrast enhancement for the raster images you need a color list of colors (as ColorRampItem objects) generated on a logarithmic function basis and its map values associated. I assumed both of them arbitrarily in my code. You also need a QgsColorRampShader and a QgsRasterShader objects.

Complete code is at follows:

from qgis.PyQt.QtGui import QColor

layer = iface.activeLayer()
renderer = layer.renderer()
provider = layer.dataProvider()

classes = [1323, 1881, 2440, 2998]  #in your case map values associated to 
                                    #colors based on a logarithmic function

#assuming that these colors were produced with a logarithmic function
colors = [ QColor('green'), QColor('red'), QColor('blue'), QColor('brown')]

color_list = [ QgsColorRampShader.ColorRampItem(classes[i], colors[i])  for i in range(4) ]

myRasterShader = QgsRasterShader()
myColorRamp = QgsColorRampShader()


myPseudoRenderer = QgsSingleBandPseudoColorRenderer(provider, 1, myRasterShader)



My raster looks as follow:

enter image description here

After running above code at Python Console of QGIS 3.4 I got result of following image:

enter image description here

| improve this answer | |
  • I am want to implement the contrast Enhancement function for QgsSingleBandGrayRender/QgsMultibandColorRender, similar to the one given in raster toolbar. I have written the following script, but on executing it on the python console, the image disappears. – Ankit Chaudhri Aug 11 '19 at 3:49

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.