I have been struggling with setting the colorshadingalgorithm
for a raster layer in QGIS with no success for the past few days. The QGIS cookbook seems to be pretty outdated.
The code that I am using is:
QgsApplication.setPrefixPath("/usr", True)
QgsApplication.initQgis()
app = QgsApplication([], True)
plotdir = r"/home/qgis_prac/"
inShp = r"/home/qgis_prac/shps/Peru_Boundary.shp"
uri = r"/home/qgis_prac/tiffs/Peru_DEM.tif"
layer = QgsRasterLayer(uri, "Peru_DEM")
QgsMapLayerRegistry.instance().addMapLayer(layer)
layer.setDrawingStyle('SingleBandPseudoColor') # main thing goes wrong here, I think
layer.ColorShadingAlgorithm(QgsRasterLayer.PseudoColorShader) # seems to do nothng. Also the setColorShadingAlgorithm is deprecated
if hasattr(layer, "setCacheImage"):
layer.setCacheImage(None)
layer.triggerRepaint()
The code goes on....
My problem is that when the script runs, it gives me an empty map with no entries in the legend. If I use the grayband shader then it works, also for the PalettedColor
(but some cells are assigned colors).
What I need is some replacement or work around setting the ColorShadingAlgorithm
.
Answer
The QGIS cookbook is pretty outdated but is possible to find out the solution when the class methods of QgsColorRampShader, QgsRasterShader and QgsSingleBandPseudoColorRenderer ('setDrawingStyle' does not work) are explored at the Python Console. I used the following code to convert a raster with a SingleBandGray render type (minimum value = 1323, maximum value = 3556) in a SingleBandPseudoColor render type with my own ColorRampShader.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
layer=iface.activeLayer()
min=1323
max =3556
range =max-min
add=range//2
int =min + add
colDic={'red':'#ff0000', 'yellow':'#ffff00','blue':'#0000ff'}
valueList =[min, int, max]
lst = [ QgsColorRampShader.ColorRampItem(valueList[0], QColor(colDic['red'])), \
QgsColorRampShader.ColorRampItem(valueList[1], QColor(colDic['yellow'])), \
QgsColorRampShader.ColorRampItem(valueList[2], QColor(colDic['blue']))]
myRasterShader = QgsRasterShader()
myColorRamp = QgsColorRampShader()
myColorRamp.setColorRampItemList(lst)
myColorRamp.setColorRampType(QgsColorRampShader.INTERPOLATED)
myRasterShader.setRasterShaderFunction(myColorRamp)
myPseudoRenderer = QgsSingleBandPseudoColorRenderer(\
layer.dataProvider(), layer.type(), myRasterShader)
layer.setRenderer(myPseudoRenderer)
iface.mapCanvas().refresh()
iface.legendInterface().refreshLayerSymbology(layer)
Initial state:
After running the code at the Python Console:
No comments:
Post a Comment