Outdated version of the documentation. Find the latest one here.

Utiliser des couches raster

This sections lists various operations you can do with raster layers.

Détails d’une couche

A raster layer consists of one or more raster bands — it is referred to as either single band or multi band raster. One band represents a matrix of values. Usual color image (e.g. aerial photo) is a raster consisting of red, blue and green band. Single band layers typically represent either continuous variables (e.g. elevation) or discrete variables (e.g. land use). In some cases, a raster layer comes with a palette and raster values refer to colors stored in the palette:

rlayer.width(), rlayer.height()
(812, 301)
rlayer.extent()
<qgis._core.QgsRectangle object at 0x000000000F8A2048>
rlayer.extent().toString()
u'12.095833,48.552777 : 18.863888,51.056944'
rlayer.rasterType()
2  # 0 = GrayOrUndefined (single band), 1 = Palette (single band), 2 = Multiband
rlayer.bandCount()
3
rlayer.metadata()
u'<p class="glossy">Driver:</p>...'
rlayer.hasPyramids()
False

Moteur de rendu

Lorsqu’un raster est chargé, il récupère un moteur de rendu par défaut basé sur son type. Ce moteur peut être modifié dans les propriétés de la couche ou par programmation.

To query the current renderer:

>>> rlayer.renderer()
<qgis._core.QgsSingleBandPseudoColorRenderer object at 0x7f471c1da8a0>
>>> rlayer.renderer().type()
u'singlebandpseudocolor'

To set a renderer use setRenderer() method of QgsRasterLayer. There are several available renderer classes (derived from QgsRasterRenderer):

  • QgsMultiBandColorRenderer
  • QgsPalettedRasterRenderer
  • QgsSingleBandColorDataRenderer
  • QgsSingleBandGrayRenderer
  • QgsSingleBandPseudoColorRenderer

Les couches rasters mono-bande peuvent être affichées soit en niveaux de gris (faibles valeurs: noir, valeurs hautes = blanc) ou avec un algorithme de pseudo-couleurs qui affecte des couleurs aux valeurs de la bande unique. Les rasters mono-bande avec une palette peut être affichés en utilisant leur palette. Les couches multi-bandes sont affichées en calquant les bandes sur les couleurs RGB. L’autre possibilité est d’utiliser juste une bande pour le niveau de gris ou la pseudo-coleur.

The following sections explain how to query and modify the layer drawing style. After doing the changes, you might want to force update of map canvas, see Refreshing Layers.

TODO:
contrast enhancements, transparency (no data), user defined min/max, band statistics

Rasters mono-bande

Let’s say we want to render our raster layer (assuming one band only) with colors ranging from green to yellow (for pixel values from 0 to 255). In the first stage we will prepare QgsRasterShader object and configure its shader function:

>>> fcn = QgsColorRampShader()
>>> fcn.setColorRampType(QgsColorRampShader.INTERPOLATED)
>>> lst = [ QgsColorRampShader.ColorRampItem(0, QColor(0,255,0)), \
    QgsColorRampShader.ColorRampItem(255, QColor(255,255,0)) ]
>>> fcn.setColorRampItemList(lst)
>>> shader = QgsRasterShader()
>>> shader.setRasterShaderFunction(fcn)

Le shader affecte les couleurs comme indiqué par sa rampe de couleur. La rampe de couleur est fournie sous forme d’une liste contenant la valeur de pixel avec sa couleur associée. Il existe trois modes d’interpolation des valeurs:

  • linear (INTERPOLATED): resulting color is linearly interpolated from the color map entries above and below the actual pixel value
  • discrete (DISCRETE): color is used from the color map entry with equal or higher value
  • exact (EXACT): color is not interpolated, only the pixels with value equal to color map entries are drawn

In the second step we will associate this shader with the raster layer:

>>> renderer = QgsSingleBandPseudoColorRenderer(layer.dataProvider(), 1, shader)
>>> layer.setRenderer(renderer)

The number 1 in the code above is band number (raster bands are indexed from one).

Rasters multi-bandes

By default, QGIS maps the first three bands to red, green and blue values to create a color image (this is the MultiBandColor drawing style. In some cases you might want to override these setting. The following code interchanges red band (1) and green band (2):

rlayer.renderer().setGreenBand(1)
rlayer.renderer().setRedBand(2)

In case only one band is necessary for visualization of the raster, single band drawing can be chosen — either gray levels or pseudocolor.

Refreshing Layers

If you do change layer symbology and would like ensure that the changes are immediately visible to the user, call these methods

if hasattr(layer, "setCacheImage"):
  layer.setCacheImage(None)
layer.triggerRepaint()

The first call will ensure that the cached image of rendered layer is erased in case render caching is turned on. This functionality is available from QGIS 1.4, in previous versions this function does not exist — to make sure that the code works with all versions of QGIS, we first check whether the method exists.

Note

This method is deprecated as of QGIS 2.18.0 and will produce a warning. Simply calling triggerRepaint() is sufficient.

The second call emits signal that will force any map canvas containing the layer to issue a refresh.

With WMS raster layers, these commands do not work. In this case, you have to do it explicitly

layer.dataProvider().reloadData()
layer.triggerRepaint()

In case you have changed layer symbology (see sections about raster and vector layers on how to do that), you might want to force QGIS to update the layer symbology in the layer list (legend) widget. This can be done as follows (iface is an instance of QgisInterface)

iface.legendInterface().refreshLayerSymbology(layer)

Interrogation des données

To do a query on value of bands of raster layer at some specified point

ident = rlayer.dataProvider().identify(QgsPoint(15.30, 40.98), \
  QgsRaster.IdentifyFormatValue)
if ident.isValid():
  print ident.results()

The results method in this case returns a dictionary, with band indices as keys, and band values as values.

{1: 17, 2: 220}