Этот раздел описывает различные действия, которые можно выполнять с растровыми слоями.
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()
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
Сразу после загрузки растровый слой отображается стилем, основанным на его типе. Стиль отображения может быть изменён в диалоге свойств растрового слоя или программным путем. Существуют следующие стили отображения:
Индекс |
Константа: QgsRasterLater.X |
Комментарий |
---|---|---|
1 | SingleBandGray | Одноканальное изображение отображается в оттенках серого цвета |
2 | SingleBandPseudoColor | Одноканальное изображение отображается с использованием псевдоцвета |
3 | PalettedColor | Одноканальное изображение отображается с использованием псевдоцвета |
4 | PalettedSingleBandGray | Слой с “палитрой”, отрисовка в оттенках серого |
5 | PalettedSingleBandPseudoColor | “Palette” layer drawn using a pseudocolor algorithm |
7 | MultiBandSingleBandGray | Слой состоит из 2 и более каналов, но отображается только один канал в оттенках серого |
8 | MultiBandSingleBandPseudoColor | Слой состоит из 2 и более каналов, но отображается только один канал с использованием псевдоцвета |
9 | MultiBandColor | Слой состоит из 2 и более каналов, установлено соответствие с цветами пространства RGB |
To query the current drawing style:
>>> rlayer.drawingStyle()
9
Одноканальные растровые слои могут отображаться либо в оттенках серого (малые значения = черный, большие значения = белый) или с использованием псевдоцвета, когда одинаковым значениям присваивается свой цвет. Кроме того, одноканальные растры могут отображаться с использованием палитры. При отображении многоканальных слоёв обычно устанавливается соответствие между каналами и цветами пространства RGB. Ещё один способ — использование одного канала для отрисовки в оттенках серого или в псевдоцвете.
В следующих разделах описано как узнать и изменить стиль отображения слоя. После того, как изменения внесены, потребуется обновить карту, см. Обновление слоёв.
They are rendered in gray colors by default. To change the drawing style to pseudocolor:
>>> rlayer.setDrawingStyle(QgsRasterLayer.SingleBandPseudoColor)
>>> rlayer.setColorShadingAlgorithm(QgsRasterLayer.PseudoColorShader)
The PseudoColorShader
is a basic shader that highlights low values in blue
and high values in red. Another, FreakOutShader
uses more fancy colors and
according to the documentation, it will frighten your granny and make your dogs
howl.
There is also ColorRampShader
which maps the colors as specified by its
color map. It has three modes of interpolation of values:
INTERPOLATED
): resulting color is linearly interpolated from the
color map entries above and below the actual pixel valueDISCRETE
): color is used from the color map entry with equal
or higher valueточный (EXACT
): цвета не интерполируются, отображаются только пиксели со значениями, равными значениям цветовой карты
Установка градиента от зеленого к желтому цвету (для значений от 0 до 255) выглядит так:
>>> rlayer.setColorShadingAlgorithm(QgsRasterLayer.ColorRampShader)
>>> lst = [ QgsColorRampShader.ColorRampItem(0, QColor(0,255,0)), \
QgsColorRampShader.ColorRampItem(255, QColor(255,255,0)) ]
>>> fcn = rlayer.rasterShader().rasterShaderFunction()
>>> fcn.setColorRampType(QgsColorRampShader.INTERPOLATED)
>>> fcn.setColorRampItemList(lst)
To return back to default gray levels, use:
>>> rlayer.setDrawingStyle(QgsRasterLayer.SingleBandGray)
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.setGreenBandName(rlayer.bandName(1))
>>> rlayer.setRedBandName(rlayer.bandName(2))
In case only one band is necessary for visualization of the raster, single band drawing can be chosen — either gray levels or pseudocolor, see previous section:
>>> rlayer.setDrawingStyle(QgsRasterLayer.MultiBandSingleBandPseudoColor)
>>> rlayer.setGrayBandName(rlayer.bandName(1))
>>> rlayer.setColorShadingAlgorithm(QgsRasterLayer.PseudoColorShader)
>>> # now set the shader
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()
Первая конструкция нужна для того, чтобы убедиться, что при использовании кеша отрисовки кешированные изображения обновляемого слоя удалены. Этот функционал доступен начиная с QGIS 1.4, в более ранних версиях такой функции нет — поэтому, в начале, чтобы быть уверенными в работоспособности кода во всех версиях QGIS, выполняется проверка на существование метода.
Вторая конструкция вызывает сигнал, который заставляет все карты, содержащие слой, выполнить перерисовку.
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)
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}