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, x, y):
        ulX = geoMatrix[0]
        ulY = geoMatrix[3]
        xDist = geoMatrix[1]
        yDist = geoMatrix[5]
        coorX = (ulX + (x * xDist))
        coorY = (ulY + (y * yDist))
        return (coorX, coorY)
    
  5. Now, we'll open the image in GDAL
    src = gdal.Open("/qgis_data/rasters/Satimage.tif")
    
  6. Next, get the GeoTransform object from the image:
    geoTrans = src.GetGeoTransform()
    
  7. Now, calculate the center pixel of the image:
    centerX = src.RasterXSize/2
    centerY = src.RasterYSize/2
    
  8. Finally, perform the conversion by calling our function:
    Pixel2world(geoTrans, centerX, centerY)
    
  9. Verify the coordinates returned are close to the following output:
    (-89.59486002580364, 30.510227817850406)
    

How it works...

Pixel conversion is just a scaling ratio between two planes, the image coordinate system and the Earth coordinate system. When dealing with large areas, this conversion can become a more complex projection because the curvature of the Earth comes into play. The GDAL website has a nice tutorial about the geotransform object at the following URL: http://www.gdal.org/gdal_tutorial.html

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

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