Skip to content

Instantly share code, notes, and snippets.

@fitnr
Last active December 17, 2021 14:11
Show Gist options
  • Save fitnr/3e2f5b8abf70780dac2613689ddbbdb9 to your computer and use it in GitHub Desktop.
Save fitnr/3e2f5b8abf70780dac2613689ddbbdb9 to your computer and use it in GitHub Desktop.
Convert between pixel/geo values with a gdal geotransform
"""
Where transform is a geotransform array, e.g.
>>> from osgeo import gdal
>>> src = gdal.Open('example.tiff')
>>> transform = src.GetGeoTransform()
>>> (-82.254, 3.0858676207514586e-05, 0.0, 41.3163, 0.0, -3.086680761099182e-05)
>>> # [x origin (left), pixel width, x skew, y origin (top), y skew, y pixel height (negative because counting from top of image)]
"""
def px2geo(geotransform, coord):
'''Convert pixel coordinates to projected geographic coordinates.'''
mx, my = coord
px = mx * geotransform[1] + geotransform[0]
py = my * geotransform[5] + geotransform[3]
return px, py
def geo2px(geotransform, point):
'''Convert geographic coordinates to pixel values.'''
x_origin, y_origin = transform[0], transform[3]
width, height = transform[1], -transform[5]
px = int((point[0] - x_origin) / width)
py = int((y_origin - point[1] ) / height)
return px, py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment