I am importing a number of rasters using the python console in QGIS 2.8. I would like to color them all using the same color map, which I have saved to a file. I would like to do this using python so that I don't have to navigate the gui for each file (i.e., right click on the layer -> properties -> style; Render type=Singleband psuedocolor; load color map from file).
My current approach is to follow the Using Raster Layers tutorial. However, I just read the contents of my color map file and convert it to the input of setColorRampItemList().
Here's my code so far
from qgis.core import QgsRasterLayer
from qgis.core import QgsColorRampShader
from PyQt4.QtCore import QFileInfo
from PyQt4.QtGui import QColor
def GetColorRampItemListFromText(file_contents):
file_contents = file_contents.split('\n')[2:] # get rid of header
file_contents = [ map(int,line.split(',')[0:4]) for line in file_contents ]
lst = [ QgsColorRampShader.ColorRampItem(line[0], QColor(line[1],line[2],line[3])) for line in file_contents ]
return lst
raster = "D:\\example.tif"
fileInfo = QFileInfo(raster)
path = fileInfo.filePath()
baseName = fileInfo.baseName()
layer = QgsRasterLayer(path, baseName)
QgsMapLayerRegistry.instance().addMapLayer(layer)
file_contents = """# QGIS Generated Color Map Export File
INTERPOLATION:INTERPOLATED
0,0,0,0,255,0.000000
1,0,255,0,255,1.000000
2,0,170,0,255,2.000000
3,170,85,0,255,3.000000
4,243,205,255,255,4.000000
5,0,255,255,255,5.000000
6,255,255,0,255,6.000000
7,255,255,255,255,7.000000
8,255,0,0,255,8.000000
9,0,0,255,255,9.000000
10,130,133,123,255,10.000000
11,11,86,29,255,11.000000
12,255,0,255,255,12.000000
13,0,0,0,255,13.000000
14,255,174,0,255,14.000000"""
lst = GetColorRampItemListFromText(file_contents)
fcn = QgsColorRampShader()
fcn.setColorRampType(QgsColorRampShader.INTERPOLATED)
fcn.setColorRampItemList(lst)
shader = QgsRasterShader()
shader.setRasterShaderFunction(fcn)
renderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, shader)
layer.setRenderer(renderer)
layer.dataProvider().reloadData()
layer.triggerRepaint()
My question is either:
- Why is my code not rendering the color table?
- Is there an easier way to apply a color table from a file?
EDIT:
The reason it wasn't rendering has something to do with layer.dataProvider().reloadData()
. Removing it works as expected.
For what it's worth, Here's another similar question and answer: Assigning Color Ramp using PyQGIS