5

Is there a way to get the XY cordinates of a pixel based on the array index using numpy/gdal?

I have a new set of extents for a raster and, based on these newer extents, want to determine the centroid of the raster (polygon). Wondering if there are any functions which can return the coordinate values based on the pixel indices.

1
  • 1
    Welcome to GIS SE! As a new user be sure to take the Tour. You have tagged your question with arcgis-10.2 but make no mention of using that software in your question body. Would you be able to edit your question to explain the relevance of that tag (or remove it), please?
    – PolyGeo
    Aug 24, 2015 at 8:42

2 Answers 2

3

Try something like that, where dx,dy are number of indexes:

from osgeo import gdal
file = gdal.Open( ’file.tif ’)

def pixel(dx,dy):
    px = file.GetGeoTransform()[0]
    py = file.GetGeoTransform()[3]
    rx = file.GetGeoTransform()[1]
    ry = file.GetGeoTransform()[5]
    x = dx/rx + px
    y = dy/ry + py
    return x,y

GetGeoTransform() function returns tuple with 6 values (coordinates of origin, resolution, angle), more in documentation.

1
  • The operator should be "*" not "/" as by the documention you link
    – lbenini
    May 17, 2016 at 14:43
2

Gdal probably has a handy function. Have you looked at these links?

But knowing that the header of the image contains the bounding coordinates and projection information, you could calculate them yourself (not recommended unless you enjoy learning things the hard way). EX: I knew my pixel size was 30m. For point 3,4 from the origin it's simple algebra: 3x30 +/- Origin's X, 4x30 +/- Origin's Y Caveats:

  • assumes you're nowhere near zone boundaries
  • not very accurate beyond locating the right pixel
  • remember to deal with negative coordinates properly (the +/- in the example)
1
  • Thanks for the links. The alternative looks promising took, :)
    – VeeJay
    Aug 24, 2015 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.