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.
We will use the SatImage raster available at:
https://geospatialpython.googlecode.com/files/SatImage.zip
Place this raster in your /qgis_data/rasters
directory.
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.
gdal
module:from osgeo import 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)
src = gdal.Open("/qgis_data/rasters/Satimage.tif")
GeoTransform
object from the image:geoTrans = src.GetGeoTransform()
centerX = src.RasterXSize/2 centerY = src.RasterYSize/2
Pixel2world(geoTrans, centerX, centerY)
(-89.59486002580364, 30.510227817850406)
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