Fourni par Blogger.

Masking a Raster in QGIS

Publié par elharrak lundi 31 mars 2014 0 commentaires

This tutorial will guide you through the process of masking or clipping a raster layer based on a vector boundary layer.  Most raster layers come in the format of a rectangle defined by the number of cells in its width and height with a value for every cell. However, when we make a map, we usually want to mask the layer according to some sort of boundary layer in the map.

For example, we have a raster layer located around the state of Florida and we would like to limit the raster to be within the state boundaries of Florida.  We will use 2 layers, the original raster layer and a vector layer of the state of Florida. The image below illustrates this process.
Raster Masking Concept


This tutorial requires you to have the GdalTools Plugin installed and enabled for QGIS. Learn how to use QGIS Plugins by following our tutorial “Using QGIS Plugins”.

Open QGIS and add your raster and vector layers. Under the Raster Menu (provided by the Gdaltools plugin), select “Clipper” to open the dialog window.

QGIS Raster Masking Clipper Dialog

Set the Input file raster to be “usa_florida_raster”.

Name the output raster as a .GeoTIFF (.tif) file called “usa_florida_raster_clipped.tif” and store it in a desirable location on your computer.

Place a check next to “No data value” and leave it set to 0. This option will make all cells outside the state boundaries transparent with no data.  If you do not check this option, all cells outside the state of Florida will have a value of 0 and will not be transparent.

Under Clipping mode, select the “Mask layer” radio button and under the Mask layer dropdown menu, select our boundary layer “usa_florida”. 
Place a check next to “Load into canvas when finished”, which will add the output to the layers.
You will notice the clipper dialog displays the command that will be run.  The command used is the gdalwarp function with the cutline option.
Click OK to execute the clipper.
Once complete, click the “Close” button to dismiss the dialog.
The masked raster layer is added to the top of the layers manager.

This beginner Quantum GIS tutorial explains how you can create a regular grid of points and sample a raster dataset to extract the individual pixel values.  This is a very basic form of raster to vector point conversion which can be useful when trying to generate contours. 

Quantum GIS does offer a Contour plugin, however the plugin requires a points dataset as the input to the tool.  Therefore, this tutorial is part 1 of a 2 part tutorial, which will explain how to use raster elevation data as input, and analyze the data in order to produce vector contour lines.

Raster Elevation Data


To start off, download the sample raster elevation data here.  This data is a small square clip of raster elevation data which has been saved in the GeoTiff format.  Save the file in a well known location, and extract the data.  Open QGIS and select Add Raster Layer, navigate to the location of your data and select dem_clip.tif, click Open.  Once the data is open in QGIS you should see some lighter white pixels (representing high elevation) and some darker black pixels (representing low elevation).  Note: If your dataset looks completely black, right click dem_clip and select Properties.  Then in the style section, in the bottom right hand corner change the Contrast Enhancement dropdown to ‘Stretch To MixMax’ and click Apply.

raster_elevation_data_in_qgis

To learn more about the dataset, right click on dem_clip in the Table of Contents and select Properties.  Select Metadata, then read through the included Metadata information, taking particular note of the pixel size of 30,-30.  Looking at the Layer Spatial Reference System, you can see that raster dataset is using a UTM projection which uses meters as the units.  Therefore we can gather that each pixel in the raster dataset is representative of 30 meters.  Close the Properties/Metadata window.

Generating Regular Points


Now that we have gathered the pixel size and unit information, we can continue on to the next process where we will generate a grid of regular points.  In QGIS select Vector > Research Tools > Regular Points.  Leave the Input Boundary Layer set to dem_clip.  In the Grid Spacing section set the point spacing value to 30, as that is the size of our raster pixels.  In order to make the regular points fall within the center of each pixel we will add an offset of half our pixel size, ie (30 / 2) = 15.  Set the Initial inset from corner (LH side) value to 15.  

qgis_regular_points_tool

Note: If you have different raster datasets make sure to use the pixel size and half of the pixel size for the regular points tool to ensure your grid of points lines up with the center of every pixel. Click the Browse button for Output Shapefile, navigate to the location of your raster dataset and save the file as regular_points.shp, click OK.

qgis_regular_points_output

Sampling Raster Dataset using Points


Before we can sample the raster data using this points set, we must install the Point sampling tool plugin for QGIS.  In QGIS select Plugins > Fetch Python Plugins, search for ‘samp’ select Point sampling tool and click Install/upgrade plugin.  Once it is installed close the Fetch Python Plugins window.  Then select Plugins > Analyses > Point sampling tool.  Set the Layer containing sampling points to use regular_points.  In the Layers with fields/bands to get values from click dem_clip so that it is highlighted.  For Output point vector layer click the Browse button, navigate to the location of your raster dataset and save the file as point_sampling.shp.  You can leave a checkbox to Add created layer to the TOC, click OK. 

qgis_point_sampling_tool

Once the tool is complete, right click on point_sampling in the TOC and select Open attribute table.  As you can see each row represents an individual point object, and they should all have the elevation value of the pixel underneath the point in the column called dem_clip.

This beginner QGIS tutorial explains how to generate contours directly from raster elevation data by using the GdalTools Contour function.  I suggest users to complete the tutorial called ‘Using QGIS Plugins’ to find out how to properly install and enable the GdalTools Python Plugin. 

qgis_point_contour_output

Once you have downloaded and extracted the raster elevation data, open up QGIS and select Add Raster Layer.  Navigate to the location of the dem_clip.tif file and add it to your current project.

Generating Contours from Raster


To generate contours directly from the raster elevation data, select Raster > Contour to open the GdalTools Contour menu.  In the Contour menu, make sure to select dem_clip as the Input file (raster).  For Output directory for contour lines (shapefile) click on the Select button.  This tool is asking for you to select the parent folder for where the output file contour.shp is to be stored.  Navigate to the location of your raster elevation data, click the Create New Folder icon and name the folder ‘rastercontour’.  Finally select the ‘rastercontour’ directory and click on the Choose button.

qgis_choose_raster_contour_ouput_directory

Back in the GdalTools Contour menu, set the Interval between contour lines to ‘100’.  Place a check next to Attribute Name and leave the name set to ELEV.  Lastly place a checkbox in the Load into canvas when finished option.  Click OK and then Close. 

qgis_gdaltools_contour_menu

You should now see your contour lines overlaid on top of your elevation raster.  In order to better symbolize your contours with graduated colors and appropriate feature labels, continue onto the tutorial titled ‘How to generate contours using point data in Quantum GIS (QGIS)’ and complete the bottom two sections: Adding Symbology to Contours and Labeling Contours.  Once you have completed the tutorial you should have a nice clear map which shows the vector contours with graduated color scheme and feature labels overlaid on top of the original raster elevation data.

qgis_point_contour_output

This advanced PostgreSQL/PostGIS tutorial will provide users with a set of two plpgsql functions: utmzone(geometry) and st_buffer_meters(geometry, double precision).  These functions will be helpful for anyone trying to buffer latitude/longitude data using meters or kilometers.  These functions have been designed to work with any projection, allowing users to buffer geometry objects using distances specified in meters for all areas of the globe.

ST_Buffer and Projections

 The PostGIS ST_Buffer function allows users to buffer any geometry objects by passing in a simple distance parameter.  This function can cause some interesting results when using dataset that use lat/long projections.  Often buffers on points that occur near the equator tend to look somewhat decent.  However, when performing the same query with data located near the poles, buffers around points will appear elongated.  The issue arises because the units for global projections are measured in radians and not meters.  In order to solve this problem we must transform the projection into one with meters as the measured units.  The UTM (WGS 84) projections cut the globe into a set of many different UTM grid zones, each being defined by a unique SRID value.  This set of projections can be used to measure distances in meters for all areas of the globe.

UTM Zone Function

The UTM Zone plpgsql function has been designed to find the correct UTM (WGS 84) SRID for a point (in any SRID).  Copy and paste the following SQL into a query window and execute the query to create the utmzone(geometry) function in your database.
/* Function: utmzone(geometry)
DROP FUNCTION utmzone(geometry);
Usage: SELECT ST_Transform(the_geom, utmzone(ST_Centroid(the_geom))) FROM sometable; */
 
CREATE OR REPLACE FUNCTION utmzone(geometry)
RETURNS integer AS
$BODY$
DECLARE
geomgeog geometry;
zone int;
pref int;
 
BEGIN
geomgeog:= ST_Transform($1,4326);
 
IF (ST_Y(geomgeog))>0 THEN
pref:=32600;
ELSE
pref:=32700;
END IF;
 
zone:=floor((ST_X(geomgeog)+180)/6)+1;
 
RETURN zone+pref;
END;
$BODY$ LANGUAGE 'plpgsql' IMMUTABLE
COST 100;
The output of this function returns an integer value of the correct UTM (WGS 84) SRID.  This function can be useful to fetch SRID values required for the initial projection transformation into meter units.  The utmzone(geometry) and other plpgsql function can be found athttp://trac.osgeo.org/postgis/wiki/UsersWikiplpgsqlfunctionsDistance.

ST_Buffer_Meters Function

 The st_buffer_meters(geometry, double precision) plpgsql function is a custom function which builds off of the utmzone(geometry) function.  The goal of this function is to transform your data into a UTM meter unit project, perform our buffer using meter units, and then transform the data back into the original projection.  The function logic is explained through the following steps:

  1. Determine the original SRID value of the geometry object
  2. Determine the correct UTM SRID value using the centroid of the geometry
  3. Transform the geometry into the UTM meter unit projection
  4. Perform the buffer using the number of meters passed through the 2ndparameter
  5. Transform the geometry back into the original SRID projection

To install the customized st_buffer_meters(geometry, double precision) plpgsql function into your database, copy and paste the following SQL into a query window and execute the query.
/* Function: ST_Buffer_Meters(geometry, double precision)
DROP FUNCTION ST_Buffer_Meters(geometry, double precision);
Usage: SELECT ST_Buffer_Meters(the_geom, num_meters) FROMsometable; */
 
 
CREATE OR REPLACE FUNCTION ST_Buffer_Meters(geometry, doubleprecision)
RETURNS geometry AS
$BODY$
DECLARE
orig_srid int;
utm_srid int;
 
BEGIN
orig_srid:= ST_SRID($1);
utm_srid:= utmzone(ST_Centroid($1));
 
RETURN ST_transform(ST_Buffer(ST_transform($1, utm_srid), $2), orig_srid);
END;
$BODY$ LANGUAGE 'plpgsql' IMMUTABLE
COST 100;
You now have the two required plpgsql functions installed on your database.  These functions are now available to use in any SQL queries you develop.  Make sure to use the following usage when executing a st_buffer_meters(geometry, double precision) query.

Simple usage
SELECT ST_Buffer_Meters(the_geom, num_meters) FROM sometable;

 Geometry with Unknown SRID -1
SELECT ST_Buffer_Meters(ST_SetSRID(the_geom, srid_value), num_meters) FROM sometable;
 Buffer objects by 500 meters
SELECT ST_Buffer_Meters(the_geom, 500) FROM sometable;
 Buffer objects using a column of meter values
SELECT ST_Buffer_Meters(the_geom, meter_colname) FROM sometable;
 Buffer objects by 10 kilometers
SELECT ST_Buffer_Meters(the_geom, 10000) FROM sometable;
 Buffer objects using a column of kilometer values
SELECT ST_Buffer_Meters(the_geom, kilometer_colname * 1000) FROM sometable;