Clipping a raster using a shapefile

Sometimes you need to use a subset of an image which covers an area of interest for a project. In fact, areas of an image outside your area of interest can distract your audience from the idea you are trying to convey. Clipping a raster to a vector boundary allows you to only use the portions of the raster you need. It can also save processing time by eliminating areas outside your area of interest.

Getting ready

We will use the SatImage raster again available at the following URL if you haven't downloaded it from previous recipes:

https://geospatialpython.googlecode.com/files/SatImage.zip

Place this raster in your /qgis_data/rasters directory.

How to do it...

Clipping is a common operation and GDAL is well suited for it.

  1. First, in the QGIS Python Console, run import the processing module:
    import processing
    
  2. Next, run the processing command specifying the input image name as the second argument and the output image as the seventh argument:
    processing.runandload("gdalogr:cliprasterbymasklayer","/qgis_data/rasters/SatImage.tif","/qgis_data/hancock/hancock.shp","none",False,False,"","/qgis_data/rasters/clipped.tif")
    
  3. Verify your output raster looks like the following screenshot:
    How to do it...

How it works...

GDAL creates a no data mask outside the shapefile boundary. To the extent of the original image remains the same, however you no longer visualize it and processing algorithms will ignore the no data values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset