Computer displays render images in the visible spectrum of red, green, and blue light (RGB). However, raster images may contain bands outside the visible spectrum. These types of rasters make poor visualizations, so you will often want to recombine the bands to change the RGB values.
For this recipe, we will use a false-color image, which you can download from https://geospatialpython.googlecode.com/files/FalseColor.zip.
Unzip this tif
file and place it in your /qgis_data/rasters
directory.
We will load this raster and swap the order of the first and second bands. Then, we will add it to the map. To do this, we need to perform the following steps:
rasterLyr = QgsRasterLayer("/qgis_data/rasters/FalseColor.tif", "Band Swap") rasterLyr.isValid()
ren = rasterLyr.renderer()
red band
to band 2
:ren.setRedBand(2)
green band
to band 1
:ren.setGreenBand(1)
QgsMapLayerRegistry.instance().addMapLayers([rasterLyr])
Load the source image into QGIS as well to compare the results. In the false-color image, vegetation appears red, while in the band-swapped image, trees appear a more natural green and the water is blue. QGIS uses the RGB order to allow you to continue to reference the bands by number. Even though band 2
is displayed first, it is still referenced as band 2
. Also, notice that the band order is controlled by a QgsMultiBandColorRenderer
object instantiated by the layer rather than the layer itself. The type of renderer that is needed is determined at load time by the data type and number of bands.
The QgsMultiBandColorRenderer()
method has other methods to control contrast enhancement for each band, such as setRedContrastEnhancement()
. You can learn more about raster renderers for different types of data in the QGIS API documentation at http://qgis.org/api/classQgsRasterRenderer.html.