2

I need to configure a pseudocolour symbology of a raster image using a colour map file in txt format using PyQGIS, how can I do it, and what class allows me to access this configuration?

This can be done manually with the buttons located at the bottom of the Layer Properties, in the pseudocolour symbology settings. The buttons highlighted in the image

enter image description here

The text file with the symbology that is generated and can be loaded by QGIS has the following content:

##Archivo de exportación de mapa de colores generado por QGIS INTERPOLATION:INTERPOLATED
0.11247780174017,215,25,28,255,0,1125
0.32547278888523601,253,174,97,255,0,3255
0.53846777603030205,255,255,192,255,0,5385
0.75146276317536798,166,217,106,255,0,7515
0.96445775032043501,26,150,65,255,0,9645

2
  • Could you add an example of the contents of such txt file? Commented Nov 23, 2022 at 12:30
  • 1
    Yes @bugmenot123 I added it to the question
    – Luis Perez
    Commented Nov 23, 2022 at 13:21

1 Answer 1

5
+200

With a useful method QgsRasterRendererUtils.parseColorMapFile you can open your text file and retrieve the shader items for your raster.

import os

from qgis.core import (
    QgsColorRampShader,
    QgsRasterRendererUtils,
    QgsRasterShader,
    QgsSingleBandPseudoColorRenderer
)

os.chdir("/your/folder/with/text/file/")
lyr = iface.activeLayer()  # your raster layer
colormapfile_name = "colormap.txt"

loading, ramp_shader_items, shader_type, errors = QgsRasterRendererUtils.parseColorMapFile(colormapfile_name)

if not loading:
    raise OSError(", ".join(errors))

shader = QgsRasterShader()
ramp_shader = QgsColorRampShader()
ramp_shader.setColorRampType(shader_type)
ramp_shader.setColorRampItemList(ramp_shader_items)
shader.setRasterShaderFunction(ramp_shader)

band = 1
renderer = QgsSingleBandPseudoColorRenderer(
    input=lyr.dataProvider(),
    band=band,
    shader=shader
)
lyr.setRenderer(renderer)
iface.mapCanvas().refreshAllLayers()

Documentation : QgsRasterRendererUtils

1
  • Thank you very much, it worked! However, there is still a problem, it is an old bug, the raster layer symbology is not updated in the layer properties window. I will raise it as a next question
    – Luis Perez
    Commented Nov 26, 2022 at 20:19

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.