1

I have almost 100 of single band grayscale rasters. Importing all of them one by one to QGIS and changing the color ramp seems laborious. Is there any PyQgis codes/function that can apply predefined color ramp to a raster? I found multiple solutions where python defines the color ramp first then apply it to the raster. Here is a great example of creating a color ramp and assigning it to raster. The CookBook has a similar example, which is -

>>> fcn = QgsColorRampShader()
>>> fcn.setColorRampType(QgsColorRampShader.INTERPOLATED)
>>> lst = [ QgsColorRampShader.ColorRampItem(0, QColor(0,255,0)), \
QgsColorRampShader.ColorRampItem(255, QColor(255,255,0)) ]
>>> fcn.setColorRampItemList(lst)
>>> shader = QgsRasterShader()
>>> shader.setRasterShaderFunction(fcn)

However, I don't want to define the color ramp. My choice of color ramp is in predefined, which is "RdBu" (Red to Blue) on a raster layer. Is there any way to do it?

  • Does it need to be through PyQgis? You could always define the style for one raster, then copy the style, select all other rasters, and paste it to them all in one go. – Cushen Jun 25 '18 at 5:18
  • @Cushen If I can complete the task in a few clicks then it would be great. Do you happen to have any resources that show how to do that? – Sourav Jun 25 '18 at 6:01
  • See posted answer below – Cushen Jun 25 '18 at 6:16
1

Do 'Manually':

  1. Add all rasters to the Canvas.

  2. Apply Raster Style to One Layer > Right Click this layer > Styles > Copy Style

  3. Select all other layers (shift and click to select all between two clicks) > Right Click > Paste Style

Do with Code:

You could also save the style to a file, add all the raster layer in a folder (.tif here) to the canvas, and then apply this style to all layers in the canvas as follows:

import glob, os
from PyQt5 import QtGui
from PyQt5.QtCore import QFileInfo
#NOTE 'PyQt4' for QGIS 2

rast_path = "C:/folderofrasters"
rasters = glob.glob(os.path.join(rast_path, "*.tif"))
print(rasters)

#to save style from a layer
#layer.saveNamedStyle(pathqml)
pathqml = 'C:/temp/rasterstyle.qml'

#ADD THE RASTER LAYERS TO THE CANVAS
for raster in rasters:
    fileInfo = QFileInfo(raster)
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()
    lyr = QgsRasterLayer(path, baseName)
    QgsProject.instance().addMapLayer(lyr)  
    #NOTE 'QgsMapLayerRegistry' for QGIS 2  

layers = QgsProject.instance().mapLayers().values()

#APPLY THE STYLE TO ALL LAYERS IN THE CANVAS
for l in layers:
    l.loadNamedStyle(pathqml)
    l.triggerRepaint()

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.