How to get the coordinates of a cell in a geotifier?
Use an affine transformation matrix that maps pixel coordinates to world coordinates. For example, use the affine package . (There are other ways to do the same using simple math.)
from affine import Affine
fname = '/path/to/raster.tif'
Here are two ways to get the matrix of affine transformation T0
. For example, using GDAL / Python:
from osgeo import gdal
ds = gdal.Open(path, gdal.GA_ReadOnly)
T0 = Affine.from_gdal(*ds.GetGeoTransform())
ds = None # close
For example, using rasterio :
import rasterio
with rasterio.open(fname, 'r') as r:
T0 = r.affine
The convention for a transform array used by GDAL ( T0
) is a pixel angle reference. You might want to reference the center of the pixels instead, so it needs to be translated to 50%:
T1 = T0 * Affine.translation(0.5, 0.5)
And now, to convert from pixel coordinates to world coordinates, multiply the coordinates by a matrix, which can be done with a simple function:
rc2xy = lambda r, c: (c, r) * T1
Now we get the coordinates for the raster in the first row, the second column (index [0, 1]
):
print(rc2xy(0, 1))
Also note that if you need to get the pixel coordinate from the world coordinate, you can use the inverted affine transformation matrix ~T0
.
source to share