래스터 레이어 사용

이 장에서는 래스터 레이어에 대해 할 수 있는 다양한 작업을 소개합니다.

레이어 상세 정보

래스터 레이어는 하나 이상의 래스터 밴드로 이루어져 있습니다. 각각 단일 밴드 또는 다중 밴드로 부릅니다. 하나의 밴드는 값들의 행렬을 나타냅니다. 일반 컬러 이미지(항공사진 등)는 빨간색, 파란색, 녹색 밴드로 이루어진 래스터입니다. 단일 밴드 레이어는 일반적으로 연속적인 변수(표고 등) 또는 불연속 변수(토지이용 등)를 나타냅니다. 어떤 경우, 래스터 레이어에 색상표가 포함돼 있어 색상표에 지정된 색상으로 래스터 값을 나타내기도 합니다.

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

Renderer

When a raster layer is loaded, it gets a default renderer based on its type. It can be altered either in raster layer properties or programmatically.

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

단일 밴드 래스터 레이어를 회색조(낮은 값=검은색, 높은 값=하얀색)로 그릴 수도 있고, 단일 밴드의 값에 색상을 배정하는 의사색채 알고리즘으로 그릴 수도 있습니다. 계단식 값(palette)을 가진 단일 밴드 래스터는 그 값에 지정된 색상표를 적용해서 그릴 수 있습니다. 다중 밴드 레이어는 일반적으로 밴드들을 RGB 색상에 매핑해서 그리지만 단 하나의 밴드만 사용해서 회색조나 의사색채 알고리즘으로 그리는 것도 가능합니다.

다음 단계에서는 레이어의 그리기 스타일을 조회 및 수정하는 방법을 설명합니다. 변경을 완료한 다음 맵 캔버스를 강제로 업데이트하고자 할 경우 레이어 새로고침 을 참조하세요.

TODO:

대비 향상, 투명처리 (널 데이터), 사용자 정의 최대값/최소값, 밴드 통계

단일 밴드 래스터

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)

The shader maps the colors as specified by its color map. The color map is provided as a list of items with pixel value and its associated color. There are three modes of interpolation of values:

  • 선형(linear) (INTERPOLATED) : 실제 픽셀값 위아래의 색상 맵 항목들로부터 선형적으로 보간된 색상이 산출됩니다.

  • 이산(discrete) (DISCRETE) : 색상 맵 항목에서 동일하거나 높은 값으로 색상이 산출됩니다.

  • 동일(exact) (EXACT) : 색상을 보간하지 않고, 색상 맵 항목과 동일한 값을 가진 픽셀만 그립니다.

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).

다중 밴드 래스터

QGIS는 기본적으로 처음 세 밴드를 각각 빨간색, 녹색, 파란색에 매핑해서 컬러 이미지를 생성합니다. (바로 MultiBandColor 그리기 스타일입니다.) 때로는 사용자가 이 설정을 바꾸고 싶을 수도 있습니다. 다음은 빨간색 밴드 (1)과 녹색 밴드 (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.

레이어 새로고침

레이어의 심볼을 변경하고 변경 사항을 즉시 사용자에게 보여주고 싶은 경우에는 다음 메소드를 호출하십시오.

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

소스의 첫번째 부분은 렌더링 캐시 옵션이 활성화된 경우 렌더링된 레이어의 캐시 이미지를 소거합니다. QGIS 1.4 버전부터 이 기능을 사용할 수 있고, 그 이전 버전에는 이 기능이 없습니다. 따라서 QGIS의 모든 버전에서 이 코드를 작동시키려면 먼저 이 메소드가 존재하는지 확인해야 합니다.

두 번째 부분은 레이어를 담고 있는 모든 맵 캔버스를 새로고침 하게 만드는 신호를 보냅니다.

WMS 래스터 레이어의 경우, 이 명령어들이 작동하지 않습니다. 이 경우 별도로 다음과 같이 하셔야 합니다.

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

레이어의 심볼을 변경한 경우 (그 방법은 래스터 및 벡터 레이어 관련 항목을 참조하세요) QGIS에서 레이어 목록(범례) 위젯에 있는 레이어 심볼을 업데이트하도록 할 수도 있습니다. 다음과 같이 하면 됩니다. (ifaceQgisInterface 클래스의 인스턴스입니다.)

iface.legendInterface().refreshLayerSymbology(layer)

값 조회

래스터 레이어의 어떤 특정 포인트의 밴드 값을 조회하려면 다음 함수를 사용하십시오.

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

이 경우 results 메소드가 키(key)로 밴드 인덱스를, 값(value)으로 밴드 값을 담은 사전식으로 정리된 목록(dictionary)을 반환합니다.

{1: 17, 2: 220}