[GIS] Find index location of a lat/lon point on a raster grid in ArcPy

arcgis-desktoparcpypython

This question has been confusing me for a while, and I'd love y'all's help.

I'm trying to find the index location on a raster (in terms of column and row#) of a specified lat/lon point.

My first thought was to find the cell value at the lat/lon point, convert the raster to a numpy array, and find the index of the point (but that's clunky, and requires each cell value to be unique…which isn't true in the raster)

#get values, assuming the extent object is already saved
raster = "raster.shp"
x_coord = extent.XMin
y_coord = extent.YMin
point = arcpy.Point(x_coord, y_coord)
cell_val = arcpy.GetCellValue_management(raster,point,"")
raster_array = numpy.array(raster)
final_index = raster_array.index(cell_val)
print final_index

But that's ungainly, and also requires the cell values to be unique in the raster (which again isn't the case)

Is there any other way to find the cell index of a pixel within a raster that corresponds to a point object?

Thanks!

Best Answer

It's quite simple unless the raster is rotated. You just need to know the x,y coordinates of the point, the pixel size (width and height) and the coordinates of the upper left (xmin,ymax) of the raster.

import arcview,arcpy

def map_to_pixel(point_x, point_y, cellx, celly, xmin, ymax):
    col = int((point_x - xmin) / cellx)
    row = int((point_y - ymax) / -celly)
    return col,row

point_x=your_x_coordinate
point_y=your_y_coordinate

dsc=arcpy.Describe(your_raster)

cellx=dsc.MeanCellHeight
celly=dsc.MeanCellWidth

xmin=dsc.extent.XMin
ymax=dsc.extent.YMax

col,row=map_to_pixel(point_x, point_y, cellx, celly, xmin, ymax)

Pixels are numbered from the top left.