5

I'm a QGIS beginner and I want to do a specific operation with Python scripts.

I have a GeoTIFF file corresponding to a raster layer with 6 bands, and each of these bands are 2 values (like 0 and 1, or 0 and 255, or 0 and 100 for example). What I need to do is to open each of this band separately.

rlayer = QgsRasterLayer("maps.geotiff", "viewed")

fcn = QgsColorRampShader()
fcn.setColorRampType(QgsColorRampShader.Interpolated)
lst = [ QgsColorRampShader.ColorRampItem(0, QColor(0,0,0)), QgsColorRampShader.ColorRampItem(100, QColor(255,0,0))]
fcn.setColorRampItemList(lst)
shader = QgsRasterShader()
shader.setRasterShaderFunction(fcn)
renderer = QgsSingleBandPseudoColorRenderer(rlayer.dataProvider(), 1, shader)
rlayer.setRenderer(renderer)

QgsProject.instance().addMapLayer(rlayer)

I write this according to the docs finding here : https://github.com/qgis/QGIS-Documentation/blob/master/docs/pyqgis_developer_cookbook/raster.rst#single-band-rasters

This works but not the optimal way but I have only two values and shader goes from 0 to 255 like we can see here:

What I want to do is to specify color only for specific value like proposed in "render type > unique value" with python scripts etc.

1 Answer 1

4

You need to convert the raster color table to paletted renderer class data. For that, use QgsPalettedRasterRenderer class.

rlayer = QgsRasterLayer("maps.geotiff", "viewed")
provider = rlayer.dataProvider()

lst = [ QgsColorRampShader.ColorRampItem(1, QColor(0,0,0)),
        QgsColorRampShader.ColorRampItem(100, QColor(255,0,0))]
        
class_data = QgsPalettedRasterRenderer.colorTableToClassData(lst) # <-

band = 1
renderer = QgsPalettedRasterRenderer(provider, band, class_data)  # <-

rlayer.setRenderer(renderer)
rlayer.triggerRepaint()

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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