I have a simple Python code that makes some calculations on rasters and give me some output rasters; I have also a style saved to color rasters based on pixel values. Is there an option to load the output (single-band) rasters with the color style I want in stead to have them in black and white?
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
b=[12.158, 13.094, 15.961, 19.553, 24.669, 29.16, 31.805, 31.615, 27.284, 22.286, 17.026, 13.31]
s=['Tmaxjan', 'Tmaxfeb','Tmaxmar','Tmaxapr','Tmaxmay','Tmaxjun','Tmaxjul','Tmaxaug','Tmaxsep','Tmaxoct','Tmaxnov','Tmaxdec']
path = '/Users/macbook/Desktop/TESI/PROGETTO/raster_T_max/'
list=[0,1,2,3,4,5,6,7,8,9,10,11]
for i in list:
rasterfile = QgsRasterLayer('/Users/macbook/Desktop/TESI/PROGETTO/DEM CAPITANATA.tif')
entries = []
ras1 = QgsRasterCalculatorEntry()
ras1.ref = 'ras@1'
ras1.raster = rasterfile
ras1.bandNumber = 1
entries.append( ras1 )
new_path = path + s[i]+ '.tif'
temperature = str(b[i]) + "+" + '(-0.007)' + '* ras@1 '
Temp = QgsRasterCalculator(temperature, new_path, 'GTiff', rasterfile.extent(), rasterfile.width(), rasterfile.height(), entries )
Temp.processCalculation()
iface.addRasterLayer(new_path)
-
You can apply either interpolated, discrete, or exact color ramp depending on your preferences using QgsColorRampShader as shown in this tutorial:opensourceoptions.com/blog/…Kartograaf– Kartograaf2021年02月10日 22:17:13 +00:00Commented Feb 10, 2021 at 22:17
2 Answers 2
If you already have a saved .qml style file which you would like to apply to your loaded raster, you can do it like this. Just change the style_path
variable to point to the location of your saved style file:
# ...the previous part of your code
Temp.processCalculation()
# add lines below
rasterlayer = iface.addRasterLayer(new_path)
# change path below to point to your saved style file
style_path = '/Users/macbook/path/to/named_style.qml'
rasterlayer.loadNamedStyle(style_path)
iface.layerTreeView().refreshLayerSymbology(rasterlayer.id())
# (Optional) if you want to expand the layer item in the legend, add the lines below
legenditem = iface.layerTreeView().model().rootGroup().findLayer(rasterlayer)
legenditem.setExpanded(True)
To add a raster layer and then apply a custom style to it:
rasterlayer = iface.addRasterLayer(rasterlayer_path)
rasterlayer.loadNamedStyle(style_path)
iface.layerTreeView().refreshLayerSymbology(rasterlayer.id())
rasterlayer.triggerRepaint()
Where: rasterlayer_path
contains the path string of the raster layer and style_path
contains the path string of the .qml QGIS Layer Style file.
For more info, see:
Explore related questions
See similar questions with these tags.