Resampling raster resolution

Resampling an image allows you to change the current resolution of an image to a different resolution. Resampling to a lower resolution, also known as downsampling, requires you to remove pixels from the image while maintaining the geospatial referencing integrity of the dataset. In the QGIS Processing Toolbox, the gdalogr:warpproject algorithm is used, which is the same as the algorithm used for reprojection.

Getting ready

We will again use the SatImage raster available at https://geospatialpython.googlecode.com/files/SatImage.zip.

Place this raster in your /qgis_data/rasters directory.

How to do it...

There's an extra step in this process, where we will get the current pixel resolution of the raster as a reference to calculate the new resolution and pass it to the algorithm. To do this, we need to perform the following steps:

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. Import the processing module:
    import processing
    
  4. Load and validate the raster layer:
    rasterLyr = QgsRasterLayer("/qgis_data/rasters/SatImage.tif", "Resample")
    rasterLyr.isValid()
    
  5. The algorithm requires projection information. We are not changing it, so just assign the current projection to a variable:
    epsg = rasterLyr.crs().postgisSrid()
    srs = "EPSG:%s" % epsg
    
  6. Get the current pixel's ground distance and multiply it by 2 to calculate half the ground resolution. We only use the X distance because in this case, it is identical to the Y distance:
    res = rasterLyr.rasterUnitsPerPixelX() * 2
    
  7. Run the resampling algorithm, specifying the algorithm name, layer reference, input and then output spatial reference system, desired resolution, resampling algorithm (0 is the nearest neighbor), any additional parameters, 0 for output raster data type, and the output filename:
    processing.runalg("gdalogr:warpreproject", rasterLyr, srs, srs, res, 0, None, 0,  "/qgis_data/rasters/resampled.tif")
    
  8. Verify that the resampled.tif image was created in your /qgis_data/rasters directory.

How it works...

It is counterintuitive at first to reduce the resolution by multiplying it. However, by increasing the spatial coverage of each pixel, it takes less pixels to cover the extent of the raster. You can easily compare the difference between the two in QGIS visually by loading both the images and zooming to an area with buildings or other detailed structures and then turning one layer off or on.

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

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