Book Image

QGIS Python Programming Cookbook

Book Image

QGIS Python Programming Cookbook

Overview of this book

Table of Contents (16 chapters)
QGIS Python Programming Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Converting a pixel location to a map coordinate


The ability to view rasters in a geospatial context relies on the conversion of pixel locations to coordinates on the ground. Sooner or later when you use Python to write geospatial programs, you'll have to perform this conversion yourself.

Getting ready

We will 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...

We will use GDAL to extract the information needed to convert pixels to coordinates and then use pure Python to perform the calculation. We'll use the center pixel of the image as the location to convert.

  1. Start QGIS.

  2. From the Plugins menu select Python Console

  3. We need to import the gdal module:

    from osgeo import gdal
    
  4. Then, we need to define the reusable function that does the conversion accepting a GDAL GeoTransform object containing the raster georeferencing information and the pixel's x,y values:

    def Pixel2world(geoMatrix...