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

` `

Integração com SIG GRASS

GRASS integration provides access to GRASS GIS databases and functionalities (see GRASS-PROJECT in Referências Bibliográficas e Web). The integration consists of two parts: provider and plugin. The provider allows to browse, manage and visualize GRASS raster and vector layers. The plugin can be used to create new GRASS locations and mapsets, change GRASS region, create and edit vector layers and analyze GRASS 2-D and 3-D data with more than 400 GRASS modules. In this section, we’ll introduce the provider and plugin functionalities and give some examples of managing and working with GRASS data.

The provider supports GRASS version 6 and 7, the plugin supports GRASS 6 and 7 (starting from QGIS 2.12). QGIS distribution may contain provider/plugin for either GRASS 6 or GRASS 7 or for both versions at the same time (binaries have different file names). Only one version of the provider/plugin may be loaded on runtime however.

Demo dataset

As an example, we will use the QGIS Alaska dataset (see section Sample Data). It includes a small sample GRASS LOCATION with three vector layers and one raster elevation map. Create a new folder called grassdata, download the QGIS ‘Alaska’ dataset qgis_sample_data.zip from http://qgis.org/downloads/data/ and unzip the file into grassdata.

More sample GRASS LOCATIONs are available at the GRASS website at http://grass.osgeo.org/download/sample-data/.

Carregando camadas raster e vetorial GRASS

If the provider is loaded in QGIS, the location item with GRASS grassLocation icon is added in the browser tree under each folder item which contains GRASS location. Go to the folder grassdata and expand location alaska and mapset demo.

You can load GRASS raster and vector layers like any other layer from the browser either by double click on layer item or by dragging and dropping to map canvas or legend.

Dica

Carregando dados GRASS

If you don’t see GRASS location item, verify in Help ‣ About ‣ Providers if GRASS vector provider is loaded.

Importing data into a GRASS LOCATION via drag and drop

This section gives an example of how to import raster and vector data into a GRASS mapset.

  1. In QGIS browser navigate to the mapset you want to import data into.
  2. In QGIS browser find a layer you want to import to GRASS, note that you can open another instance of the browser (Browser Panel (2)) if source data are too far from the mapset in the tree.
  3. Drag a layer and drop it on the target mapset. The import may take some time for larger layers, you will see animated icon import in front of new layer item until the import finishes.

When raster data are in different CRS, they can be reprojected using an Approximate (fast) or Exact (precise) transformation. If a link to the source raster is created (using r.external), the source data are in the same CRS and the format is known to GDAL, the source data CRS will be used. You can set these options in the Browser tab in Opções do GRASS.

If a source raster has more bands, a new GRASS map is created for each layer with .<band number> suffix and group of all maps with rasterGroup icon is created. External rasters have a different icon rasterLink.

Managing GRASS data in QGIS Browser

  • Copying maps: GRASS maps may be copied between mapsets within the same location using drag and drop.
  • Deleting maps: Right click on a GRASS map and select Delete from context menu.
  • Renaming maps: Right click on a GRASS map and select Rename from context menu.

Opções do GRASS

GRASS options may be set in GRASS Options dialog, which can be opened by right clicking on the location or mapset item in the browser and then choosing GRASS Options.

Iniciando o complemento GRASS

To use GRASS functionalities in QGIS, you must select and load the GRASS plugin using the Plugin Manager. To do this, go to the menu Plugins ‣ showPluginManager Manage and Install Plugins..., select checkbox GRASS and click [OK].

The following main features are provided with the GRASS menu (Plugins ‣ GRASS) when you start the GRASS plugin:

  • grassOpenMapset Open Mapset
  • grassNewMapset New Mapset
  • grassCloseMapset Close Mapset
  • grassTools Open GRASS Tools
  • grassRegion Display Current GRASS Region
  • general GRASS Options

Opening GRASS mapset

A GRASS mapset must be opened to get access to GRASS Tools in the plugin (the tools are disabled if no mapset is open). You can open a mapset from the browser: right click on mapset item and then choose Open mapset from context menu.

Localização e MAPSET GRASS

GRASS data are stored in a directory referred to as GISDBASE. This directory, often called grassdata, must be created before you start working with the GRASS plugin in QGIS. Within this directory, the GRASS GIS data are organized by projects stored in subdirectories called LOCATIONs. Each LOCATION is defined by its coordinate system, map projection and geographical boundaries. Each LOCATION can have several MAPSETs (subdirectories of the LOCATION) that are used to subdivide the project into different topics or subregions, or as workspaces for individual team members (see Neteler & Mitasova 2008 in Referências Bibliográficas e Web). In order to analyse vector and raster layers with GRASS modules, you generally have to import them into a GRASS LOCATION. (This is not strictly true – with the GRASS modules r.external and v.external you can create read-only links to external GDAL/OGR-supported datasets without importing them. This is not the usual way for beginners to work with GRASS, therefore this functionality will not be described here.)

../../../_images/grass_location1.png

Dados GRASS em LOCATION alaska

Importando dados para uma localização GRASS

See section Importing data into a GRASS LOCATION via drag and drop to find how data can be easily imported by dragging and dropping in the browser.

This section gives an example of how to import raster and vector data into the ‘alaska’ GRASS LOCATION provided by the QGIS ‘Alaska’ dataset in traditional way, using standard GRASS modules. Therefore, we use the landcover raster map landcover.img and the vector GML file lakes.gml from the QGIS ‘Alaska’ dataset (see Sample Data).

  1. Start QGIS and make sure the GRASS plugin is loaded.
  2. In the GRASS toolbar, click the grassOpenMapset Open MAPSET icon to bring up the MAPSET wizard.
  3. Select as GRASS database the folder grassdata in the QGIS Alaska dataset, as LOCATION ‘alaska’, as MAPSET ‘demo’ and click [OK].
  4. Now click the grassTools Open GRASS tools icon. The GRASS Toolbox (see section Ferramentas GRASS) dialog appears.
  5. Para importar o mapa raster: arquivo: landcover.img, clique no módulo: arquivo:` r.in.gdal` no: guilabel: guia módulos em árvore. Este módulo GRASS permite importar arquivos raster GDAL que suporta GRASS: arquivo: ‘local’. O módulo para: arquivo: aparece r.in.gdal.

  6. Browse to the folder raster in the QGIS ‘Alaska’ dataset and select the file landcover.img.
  7. As raster output name, define landcover_grass and click [Run]. In the Output tab, you see the currently running GRASS command r.in.gdal -o input=/path/to/landcover.img output=landcover_grass.
  8. When it says Successfully finished, click [View output]. The landcover_grass raster layer is now imported into GRASS and will be visualized in the QGIS canvas.
  9. Para importar o arquivo vetorial GML: arquivo lakes.gml, clique no módulo: arquivo:` v.in.ogr` no: guilabel: módulos em árvores. Este módulo GRASS permite importar arquivos vetoriais OGR apoiados na GRASS: arquivo: local. A caixa de diálogo para o arquivo aparece v.in.ogr.

  10. Browse to the folder gml in the QGIS ‘Alaska’ dataset and select the file lakes.gml as OGR file.
  11. As vector output name, define lakes_grass and click [Run]. You don’t have to care about the other options in this example. In the Output tab you see the currently running GRASS command v.in.ogr -o dsn=/path/to/lakes.gml output=lakes\_grass.
  12. When it says Succesfully finished, click [View output]. The lakes_grass vector layer is now imported into GRASS and will be visualized in the QGIS canvas.

Criando uma nova Localização GRASS

As an example, here is the sample GRASS LOCATION alaska, which is projected in the Albers Equal Area projection using feet as units. This sample GRASS LOCATION alaska will be used for all examples and exercises in the following GRASS-related sections. It is useful to download and install the dataset on your computer (see Sample Data).

  1. Start QGIS and make sure the GRASS plugin is loaded.
  2. Visualize the alaska.shp shapefile (see section Loading a layer from a file) from the QGIS Alaska dataset (see Sample Data).
  3. In the GRASS toolbar, click on the grassNewMapset New mapset icon to bring up the MAPSET wizard.
  4. Select an existing GRASS database (GISDBASE) folder grassdata, or create one for the new LOCATION using a file manager on your computer. Then click [Next].
  5. We can use this wizard to create a new MAPSET within an existing LOCATION (see section Adicionando um novo MAPSET) or to create a new LOCATION altogether. Select radioButtonOn Create new location (see figure_grass_new_location).
  6. Enter a name for the LOCATION – we used ‘alaska’ – and click [Next].
  7. Define the projection by clicking on the radio button radioButtonOn Projection to enable the projection list.
  8. We are using Albers Equal Area Alaska (feet) projection. Since we happen to know that it is represented by the EPSG ID 2964, we enter it in the search box. (Note: If you want to repeat this process for another LOCATION and projection and haven’t memorized the EPSG ID, click on the projectionEnabled CRS Status icon in the lower right-hand corner of the status bar (see section Trabalhando com Projeções)).
  9. Na Filtro, insira 2964 para selecionar a projeção.

  10. Click [Next].
  11. To define the default region, we have to enter the LOCATION bounds in the north, south, east, and west directions. Here, we simply click on the button [Set current QGIS extent], to apply the extent of the loaded layer alaska.shp as the GRASS default region extent.
  12. Click [Next].
  13. We also need to define a MAPSET within our new LOCATION (this is necessary when creating a new LOCATION). You can name it whatever you like - we used ‘demo’. GRASS automatically creates a special MAPSET called PERMANENT, designed to store the core data for the project, its default spatial extent and coordinate system definitions (see Neteler & Mitasova 2008 in Referências Bibliográficas e Web).
  14. Check out the summary to make sure it’s correct and click [Finish].
  15. O novo: arquivo ‘LOCALIZAÇÃO’: ‘Alaska’, e dois: arquivos: CONJUNTO DE MAPAS, demonstração e” permanente ”, são criados. O conjunto de trabalho aberto no momento é ‘demonstração’, como você definiu.

  16. Note que algumas das ferramentas na barra de ferramentas GRASS que foram desativadas estão agora habilitadas.

../../../_images/create_grass_location.png

Creating a new GRASS LOCATION or a new MAPSET in QGIS

If that seemed like a lot of steps, it’s really not all that bad and a very quick way to create a LOCATION. The LOCATION ‘alaska’ is now ready for data import (see section Importando dados para uma localização GRASS). You can also use the already-existing vector and raster data in the sample GRASS LOCATION ‘alaska’, included in the QGIS ‘Alaska’ dataset Sample Data, and move on to section O modelo de dados vetorial do GRASS.

Adicionando um novo MAPSET

A user has write access only to a GRASS MAPSET which he or she created. This means that besides access to your own MAPSET, you can read maps in other users’ MAPSETs (and they can read yours), but you can modify or remove only the maps in your own MAPSET.

Todos: arquivos: ‘CONJUNTO DE MAPAS’ inclui um arquivo ‘WIND’ que armazena as coordenadas dos valores e a resolução selecionada (ver Neteler & Mitasova de 2008, em: ref:` literatura web` e seção: ref: sec_regiao_grass) .

  1. Start QGIS and make sure the GRASS plugin is loaded.
  2. In the GRASS toolbar, click on the grassNewMapset New mapset icon to bring up the MAPSET wizard.
  3. Selecione a pasta do banco de dados GRASS (GISDBASE): arquivo grassdata com o arquivo:` local` ‘Alaska’, onde queremos adicionar mais um: arquivo: CONJUNTO DE MAPAS chamado ‘teste’.

  4. Click [Next].
  5. We can use this wizard to create a new MAPSET within an existing LOCATION or to create a new LOCATION altogether. Click on the radio button radioButtonOn Select location (see figure_grass_new_location) and click [Next].
  6. Digite o nome: arquivo: texte para o novo: arquivo:` CONJUNTO DE MAPAS`. Abaixo no assistente, você verá uma lista existente arquivo: CONJUNTO DE MAPAS e seus proprietários

  7. Click [Next], check out the summary to make sure it’s all correct and click [Finish].

O modelo de dados vetorial do GRASS

It is important to understand the GRASS vector data model prior to digitizing. In general, GRASS uses a topological vector model. This means that areas are not represented as closed polygons, but by one or more boundaries. A boundary between two adjacent areas is digitized only once, and it is shared by both areas. Boundaries must be connected and closed without gaps. An area is identified (and labelled) by the centroid of the area.

Além de limites e centróides, um mapa vetor também pode conter pontos e linhas. Todos estes elementos de geometria podem ser misturados em um vetor e será representado em diferentes ‘camadas’ dentro de um GRASS vetor. Então, no GRASS, uma camada não é um vetor ou raster, mas um nível dentro de uma camada vetorial. Isso é importante para distinguir cuidadosamente. (Embora seja possível misturar elementos de geometria, é incomum e, mesmo no GRASS, utilizado somente em casos especiais, tais como rede de análise vetorial. Normalmente, você deve preferir armazenar diferentes elementos geométricos em diferentes camadas.)

É possível armazenar várias “camadas” em um conjunto de dados vetoriais. Por exemplo, campos, florestas e lagos pode ser armazenado em um vetor. Uma floresta adjacente e um lago podem compartilhar o mesmo limite, mas eles têm tabelas de atributos separados. Também é possível fixar atributos limites. Um exemplo pode ser o caso em que a fronteira entre um lago e uma floresta é um caminho, para que ele possa ter uma tabela de atributos diferentes.

A “camada” do recurso é definido pela “camada” dentro do GRASS. ‘Camada’ é o número que define, se houver mais do que uma camada interior do conjunto de dados (por exemplo, se a geometria for uma floresta ou lago). Por enquanto, ele pode ser apenas um número. No futuro, o GRASS também apoiará nomes como campos na interface do usuário.

Attributes can be stored inside the GRASS LOCATION as dBase, SQLite3 or in external database tables, for example, PostgreSQL, MySQL, Oracle, etc.

Atributos em tabelas de base de dados estão ligados a elementos geométricos usando um valor ‘categoria’.

‘Categoria’ (chave, ID) é um número inteiro ligado a geometrias primitivas, e que é usada como ligação a uma coluna chave na tabela de base de dados.

Dica

Aprendendo um Modelo Vetor GRASS

The best way to learn the GRASS vector model and its capabilities is to download one of the many GRASS tutorials where the vector model is described more deeply. See http://grass.osgeo.org/documentation/manuals/ for more information, books and tutorials in several languages.

Criando uma nova camada vetorial GRASS

To create a new GRASS vector layer, select one of following items from mapset context menu in the browser:

  • New Point Layer
  • New Line Layer
  • New Polygon Layer

and enter a name in the dialog. A new vector map will be created and layer will be added to canvas and editing started. Selecting type of the layer does not restrict geometry types which can be digitized in the vector map. In GRASS, it is possible to organize all sorts of geometry types (point, line and polygon) in one vector map. The type is only used to add the layer to the canvas, because QGIS requires a layer to have a specific type.

It is also possible to add layers to existing vector maps selecting one of the items described above from context menu of existing vector map.

In GRASS, it is possible to organize all sorts of geometry types (point, line and area) in one layer, because GRASS uses a topological vector model, so you don’t need to select the geometry type when creating a new GRASS vector. This is different from shapefile creation with QGIS, because shapefiles use the Simple Feature vector model (see section Creating new vector layers).

Digitalizando e editando uma camada vetorial GRASS

GRASS vector layers can be digitized using the standard QGIS digitizing tools. There are however some particularities, which you should know about, due to

  • GRASS topological model versus QGIS simple feature
  • complexity of GRASS model
    • multiple layers in single maps
    • multiple geometry types in single map
    • geometry sharing by multiple features from multiple layers

The particularities are discussed in the following sections.

Save, discard changes, undo, redo

Aviso

All the changes done during editing are immediately written to vector map and related attribute tables.

Changes are written after each operation, it is however, possible to do undo/redo or discard all changes when closing editing. If undo or discard changes is used, original state is rewritten in vector map and attribute tables.

There are two main reasons for this behaviour:

  • It is the nature of GRASS vectors coming from conviction that user wants to do what he is doing and it is better to have data saved when the work is suddenly interrupted (for example, blackout)
  • Necessity for effective editing of topological data is visualized information about topological correctness, such information can only be acquired from GRASS vector map if changes are written to the map.

Barra de Ferramentas

The ‘Digitizing Toolbar’ has some specific tools when a GRASS layer is edited:

Ícone

Ferramenta

Propósito

capturePoint

Novo Ponto

Digitaliza novo ponto

captureLine

Nova Linha

Digitaliza nova linha

captureBoundary

Nova Fronteira

Digitize new boundary
captureCentroid

Novo Centróide

Digitaliza novo centróide (etiqueta da área existente)

capturePolygon New Closed Boundary Digitize new closed boundary

Table GRASS Digitizing: GRASS Digitizing Tools

Dica

Digitalizando polígonos no GRASS

If you want to create a polygon in GRASS, you first digitize the boundary of the polygon. Then you add a centroid (label point) into the closed boundary. The reason for this is that a topological vector model links the attribute information of a polygon always to the centroid and not to the boundary.

Category

Category, often called cat, is sort of ID. The name comes from times when GRASS vectors had only singly attribute “category”. Category is used as a link between geometry and attributes. A single geometry may have multiple categories and thus represent multiple features in different layers. Currently it is possible to assign only one category per layer using QGIS editing tools. New features have automatically assigned new unique category, except boundaries. Boundaries usually only form areas and do not represent linear features, it is however possible to define attributes for a boundary later, for example in different layer.

New categories are always created only in currently being edited layer.

It is not possible to assign more categories to geometry using QGIS editing, such data are properly represented as multiple features, and individual features, even from different layers, may be deleted.

Attributes

Attributes of currently edited layer can only be modified. If the vector map contains more layers, features of other layers will have all attributes set to ‘<not editable (layer #)>’ to warn you that such attribute is not editable. The reason is, that other layers may have and usually have different set of fields while QGIS only supports one fixed set of fields per layer.

If a geometry primitive does not have a category assigned, a new unique category is automatically assigned and new record in attribute table is created when an attribute of that geometry is changed.

Dica

If you want to do bulk update of attributes in table, for example using ‘Field Calculator’ (Using the Field Calculator), and there are features without category which you don’t want to update (typically boundaries), you can filter them out by setting ‘Advanced Filter’ to cat is not null.

Editing style

The topological symbology is essential for effective editing of topological data. When editing starts, a specialized ‘GRASS Edit’ renderer is set on the layer automatically and original renderer is restored when editing is closed. The style may be customized in layer properties ‘Style’ tab. The style can also be stored in project file or in separate file as any other style. If you customize the style, do not change its name, because it is used to reset the style when editing is started again.

Dica

Do not save project file when the layer is edited, the layer would be stored with ‘Edit Style’ which has no meaning if layer is not edited.

The style is based on topological information which is temporarily added to attribute table as field ‘topo_symbol’. The field is automatically removed when editing is closed.

Dica

Do not remove ‘topo_symbol’ field from attribute table, that would make features invisible because the renderer is based on that column.

Snapping

To form an area, vertices of connected boundaries must have exactly the same coordinates. This can be achieved using snapping tool only if canvas and vector map have the same CRS. Otherwise, due conversion from map coordinates to canvas and back, the coordinate may become slightly different due to representation error and CRS transformations.

Dica

Use layer’s CRS also for canvas when editing.

Limitations

Simultaneous editing of multiple layers within the same vector at the same time is not supported. This is mainly due to the impossibility of handling multiple undo stacks for a single data source.

nix osx On Linux and macOS only one GRASS layer can be edited at time. This is due to a bug in GRASS which does not allow to close database drivers in random order. This is being solved with GRASS developers.

Dica

GRASS Edita Permissões

Você deve ser o proprietário do GRASS: arquivo: ‘CONJUNTO DE MAPAS’ que deseja editar. É impossível editar camadas de dados em: arquivo: ‘CONJUNTO DE MAPAS’ que não é seu, mesmo que você tenha permissão de gravação.

A ferramenta região GRASS

A região (definição de uma janela de trabalho espacial) no GRASS é importante para trabalhar com camadas. Análise Vetorial é, por padrão, não se limitando a quaisquer definições de região definida. Mas todos os vetores recém-criados terá a extensão espacial e a resolução da região GRASS atualmente definido, independentemente da sua extensão e da resolução original. A região GRASS atual é armazenado no: arquivo: ‘$ LOCAL / $ mapset / WIND’, e define o norte, sul, leste e oeste como limites, o número de colunas e linhas, resolução espacial horizontal e vertical.

It is possible to switch on and off the visualization of the GRASS region in the QGIS canvas using the grassRegion Display current GRASS region button.

The region can be modified in ‘Region’ tab in ‘GRASS Tolls’ dock widget. Type in the new region bounds and resolution, and click [Apply]. If you click on [Select the extent by dragging on canvas] you can select a new region interactively with your mouse on the QGIS canvas dragging a rectangle.

O módulo GRASS: arquivo: g.região fornece muito mais parâmetros para definir uma medida para a região e resolução adequados para sua análise. Você pode usar esses parâmetros com as Ferramentas GRASS, descrito na seção: ref: subseção_grass_ferramentas.

Ferramentas GRASS

The grassTools Open GRASS Tools box provides GRASS module functionalities to work with data inside a selected GRASS LOCATION and MAPSET. To use the GRASS Toolbox you need to open a LOCATION and MAPSET that you have write permission for (usually granted, if you created the MAPSET). This is necessary, because new raster or vector layers created during analysis need to be written to the currently selected LOCATION and MAPSET.

../../../_images/grass_toolbox_moduletree.png

GRASS Toolbox and Module Tree

Trabalhando com módulos GRASS

O comando GRASS dentro do GRASS Ferramentas fornece acesso a quase todos os módulos (mais de 300) grass em uma interface de linha de comando. Para oferecer um ambiente de trabalho mais amigável, cerca de 200 dos módulos GRASS disponíveis e funcionalidades também são fornecidos por gráficos dentro do plugin Ferramentas GRASS.

A complete list of GRASS modules available in the graphical Toolbox in QGIS version 2.18 is available in the GRASS wiki at http://grass.osgeo.org/wiki/GRASS-QGIS_relevant_module_list.

Também é possível personalizar o conteúdo Ferramentas GRASS. Este procedimento é descrito na seção: ref: sec_customizacao_ferramentas.

As shown in figure_grass_toolbox, you can look for the appropriate GRASS module using the thematically grouped Modules Tree or the searchable Modules List tab.

Clicando em um ícone do módulo gráfico, uma nova aba será adicionada ao diálogo da caixa de ferramentas, oferecendo três novas sub-abas :guilabel: ‘Opções’, :guilabel:’Saída’ e :guilabel:’Manual’.

Opções

The Options tab provides a simplified module dialog where you can usually select a raster or vector layer visualized in the QGIS canvas and enter further module-specific parameters to run the module.

../../../_images/grass_module_option.png

GRASS Toolbox Module Options

The provided module parameters are often not complete to keep the dialog simple. If you want to use further module parameters and flags, you need to start the GRASS shell and run the module in the command line.

A new feature since QGIS 1.8 is the support for a Show Advanced Options button below the simplified module dialog in the Options tab. At the moment, it is only added to the module v.in.ascii as an example of use, but it will probably be part of more or all modules in the GRASS Toolbox in future versions of QGIS. This allows you to use the complete GRASS module options without the need to switch to the GRASS shell.

Saída

../../../_images/grass_module_output.png

GRASS Toolbox Module Output

The Output tab provides information about the output status of the module. When you click the [Run] button, the module switches to the Output tab and you see information about the analysis process. If all works well, you will finally see a Successfully finished message.

Manual

../../../_images/grass_module_manual.png

GRASS Toolbox Module Manual

A: guilabel: ‘Manual’ mostra a página de ajuda em HTML do módulo grass. Você pode usá-lo para verificar outros parâmetros do módulo e sinalizadores ou para obter um conhecimento mais profundo sobre o objetivo do módulo. No final de cada página do manual, você vê outras ligações a: arquivo: ‘Ajuda’, o arquivo: ‘Temática’ e do: arquivo: ‘Completo’. Estas ligações fornecem a mesma informação que o módulo: arquivo: g.manual.

Dica

Mostra Resultados Imediatamente

Se você quiser exibir os resultados de cálculo imediatamente em sua tela do mapa, você pode usar o botão “Ver Saída” na parte inferior da aba módulo.

Exemplos de módulos GRASS

Os exemplos seguintes demonstrarão o poder de alguns dos módulos grama.

Criando linhas de contorno

O primeiro exemplo cria um mapa de contorno vetorial de elevação (DEM). Aqui, presume-se que você tem o Alasca: arquivo: ‘local’ configurado como explicado na seção: ref:` sec_import_loc_data

  • First, open the location by clicking the grassOpenMapset Open mapset button and choosing the Alaska location.
  • Now open the Toolbox with the grassTools Open GRASS tools button.
  • Na lista de categorias de ferramentas, clique duas vezes no: menu: ‘Raster -> Gestão de Superfície -> Gerar linhas de contorno do vetor’.

  • Now a single click on the tool r.contour will open the tool dialog as explained above (see Trabalhando com módulos GRASS).
  • In the Name of input raster map enter gtopo30.
  • Type into the Increment between Contour levels selectNumber the value 100. (This will create contour lines at intervals of 100 meters.)
  • Digite no :guilabel: Nome para a saída do vetor mapa o nome ctour_100.

  • Click [Run] to start the process. Wait for several moments until the message Successfully finished appears in the output window. Then click [View Output] and [Close].

Como se trata de uma grande região, vai demorar um pouco para exibir. Depois de terminar a renderização, você pode abrir a janela de propriedades da camada para alterar a cor da linha para que os contornos apareçam claramente sobre o raster elevação, como em: ref: vector_properties_dialog.

Em seguida, amplie uma pequena área montanhosa no centro do Alasca. Aproxima-se, você vai notar que os contornos têm cantos afiados. GRASS oferece a ferramenta v.generalize para alterar ligeiramente mapas vetoriais, mantendo sua forma original. A ferramenta usa diversos algoritmos diferentes, com finalidades diferentes. Alguns dos algoritmos (ie, Douglas Peuker e redução da Vertex) simplificam a linha removendo alguns dos vértices. O vetor resultante irá carregar mais rápido. Este processo é útil quando você tem um vetor altamente detalhado, mas você está criando um mapa muito pequena em escala, de modo que o detalhe é desnecessário.

Dica

A ferramenta simplificar

Note that QGIS has a Vector ‣ Geometry Tools ‣ Simplify geometries tool that works just like the GRASS v.generalize Douglas-Peuker algorithm.

No entanto, o objetivo do exemplo é diferente. As linhas de contorno criado pelo “r.contour” têm ângulos agudos que devem ser suavizadas. Entre o algoritmo ** v.generalize ** , há Chaiken que faz exatamente isso (também ranhuras de Hermite). Esteja ciente de que estes algoritmos podem ** adicionar vértices** ao vetor, fazendo-a carregar ainda mais lentamente.

  • Abra o GRASS Ferramentas e clique duas vezes na categoria: menu: ‘Vetor -> Desenvolver mapa -> Geral’, em seguida, clique no módulo v.generalize para abrir a janela de opções.

  • Verifique se o vetor ‘ctour_100’ aparece como Nome do vetor de entrada.

  • From the list of algorithms, choose Chaiken’s. Leave all other options at their default, and scroll down to the last row to enter in the field Name for output vector map ‘ctour_100_smooth’, and click [Run].
  • The process takes several moments. Once Successfully finished appears in the output windows, click [View output] and then [Close].
  • É possível mudar a cor do vetor para apresentar claramente o fundo matricial e para contrastar com as linhas de contorno originais. Você notará que as novas linhas de contorno têm cantos mais suaves do que o original, enquanto permanecer fiel à forma geral de origem.

../../../_images/grass_toolbox_vgeneralize.png

GRASS module v.generalize to smooth a vector map

Dica

Outros usos para r.contour

O processo descrito acima pode ser utilizado em outras situações equivalentes. Se você tem um mapa de dados de precipitação, por exemplo, então o mesmo método será utilizado para criar um mapa de vetor de linhas (chuvas constantes).

Criando um efeito de sombreamento 3D

Vários métodos são usados ​​para exibir as camadas de elevação e dar um efeito 3-D para mapas. O uso de curvas de nível, como mostrado acima, é um método popular, muitas vezes escolhido para produzir mapas topográficos. Outra forma de apresentar um efeito 3-D é de sombreamento. O efeito Sombra é criado a partir de um DEM (elevação) que calcula a inclinação e o aspecto de cada célula, em seguida, simula a posição do sol no céu dando um valor de reflexo para cada célula. Assim, você tem pistas virada para o sol; as encostas viradas longe do sol (na sombra) são escurecidas.

  • Comece este exemplo carregando o ‘raster de elevação gtopo30’. Inicie o GRASS Ferramentas, e sob a categoria Raster, clique duas vezes para abrir: menu: ‘Análise espacial -> Análise do Terreno’.

  • Então, clique r.shaded.relief para abrir o módulo.

  • Change the azimuth angle selectNumber 270 to 315.
  • Enter gtopo30_shade for the new hillshade raster, and click [Run].
  • Quando o processo termina, adicione o raster sombreado ao mapa. Você deve vê-lo exibido em escala de cinza.

  • Para visualizar tanto o sombreamento da colina e as cores do “gtopo30”, mova o mapa sombreado abaixo “mapa gtopo30” na tabela de conteúdo, em seguida, abra o: menu: ‘Propriedades de’ `“GTOPO30”, mude para o: guilabel: ‘transparência’: e defina seu nível de transparência a cerca de 25%.

Agora você deve ter a elevação gtopo30 com o seu mapa de cores e configuração de transparência apresentada acima o tons de cinza mapa sombreado. Para ver os efeitos visuais do sombreamento, desligue o mapa gtopo30_shade em seguida, ligue-o novamente.

Usando a linha de comando GRASS

The GRASS plugin in QGIS is designed for users who are new to GRASS and not familiar with all the modules and options. As such, some modules in the Toolbox do not show all the options available, and some modules do not appear at all. The GRASS shell (or console) gives the user access to those additional GRASS modules that do not appear in the Toolbox tree, and also to some additional options to the modules that are in the Toolbox with the simplest default parameters. This example demonstrates the use of an additional option in the r.shaded.relief module that was shown above.

../../../_images/grass_toolbox_shell.png

The GRASS shell, r.shaded.relief module

O módulo ** r.shaded.relief ** pode ter um parâmetro “zmult”, que multiplica os valores de elevação em relação ao XY unidades de coordenadas de modo a que o efeito de sombreamento é ainda a mais usada.

  • Load the gtopo30 elevation raster as above, then start the GRASS Toolbox and click on the GRASS shell. In the shell window, type the command r.shaded.relief map=gtopo30 shade=gtopo30_shade2 azimuth=315 zmult=3 and press [Enter].
  • After the process finishes, shift to the Browse tab and double-click on the new gtopo30_shade2 raster to display it in QGIS.
  • Como explicado acima, mova o raster com o relevo sombreado abaixo da tabela de conteúdo “raster gtopo30” em seguida, verifique a transparência da “camada gtopo30” colorida. Você deverá ver que o efeito 3-D se destaca mais fortemente em relação ao primeiro mapa com relevo sombreado.

../../../_images/grass_toolbox_shadedrelief.png

Displaying shaded relief created with the GRASS module r.shaded.relief

Estatísticas Raster em um mapa vetor

O próximo exemplo mostra como um módulo GRASS pode agregar dados raster e adicionar colunas de estatísticas para cada polígono em um mapa vetor.

  • Again using the Alaska data, refer to Importando dados para uma localização GRASS to import the trees shapefile from the shapefiles directory into GRASS.
  • Agora, um passo intermediário é necessária: centroides deve ser adicionado ao mapa importando as árvores para torná-lo num vetor de área de grass completo (incluindo os limites e centróide).

  • Na caixa de ferramentas, escolha: menu: `Vetor -> Gerenciar recursos, e abra o módulo ** v.centroids **.

  • Digite como mapa vetor de saída ‘forest_areas’ e rode o módulo.

  • Now load the forest_areas vector and display the types of forests - deciduous, evergreen, mixed - in different colors: In the layer Properties window, Symbology tab, choose from Legend type selectString ‘Unique value’ and set the Classification field to ‘VEGDESC’. (Refer to the explanation of the symbology tab in Style Properties of the vector section.)
  • Em seguida, reabrir o GRASS Ferramentas no: menu: ‘Vetor -> Atualização do Vetor’ para outros mapas.

  • Clique no módulo v.rast.stats. Digite “gtopo30” e “forest_areas”.

  • Only one additional parameter is needed: Enter column prefix elev, and click [Run]. This is a computationally heavy operation, which will run for a long time (probably up to two hours).
  • Finalmente, abra o “areas_floresta” na tabela de atributos, e verifique que várias novas colunas foram adicionadas, incluindo ` elev_min``, `` elev_max``, `` elev_média``, etc, para cada polígono florestal.

Personalizando a caixa de ferramentas GRASS

Quase todos os módulos de GRASS podem ser adicionados a caixa de ferramentas. Uma interface XML é fornecido para analisar os arquivos mais simples que configuram a aparência e os parâmetros dos módulos dentro da caixa de ferramentas.

Um exemplo de arquivo XML para gerar o módulo v.buffer (v.buffer.qgm) se parece com isto:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE qgisgrassmodule SYSTEM "http://mrcc.com/qgisgrassmodule.dtd">

<qgisgrassmodule label="Vector buffer" module="v.buffer">
        <option key="input" typeoption="type" layeroption="layer" />
        <option key="buffer"/>
        <option key="output" />
</qgisgrassmodule>

The parser reads this definition and creates a new tab inside the Toolbox when you select the module. A more detailed description for adding new modules, changing a module’s group, etc., can be found on the QGIS wiki at http://hub.qgis.org/projects/quantum-gis/wiki/Adding_New_Tools_to_the_GRASS_Toolbox.