Swapping raster bands

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.

Getting ready

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.

How to do it...

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:

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. In the Python Console, load the layer and ensure that it is valid:
    rasterLyr = QgsRasterLayer("/qgis_data/rasters/FalseColor.tif", "Band Swap")
    rasterLyr.isValid()
    
  4. Now, we must access the layer renderer in order to manipulate the order of the bands displayed. Note that this change does not affect the underlying data:
    ren = rasterLyr.renderer()
    
  5. Next, we will set the red band to band 2:
    ren.setRedBand(2)
    
  6. Now, we will set the green band to band 1:
    ren.setGreenBand(1)
    
  7. Finally, add the altered raster layer to the map:
    QgsMapLayerRegistry.instance().addMapLayers([rasterLyr])
    

How it works...

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.

There's more...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset