Geographic coordinates to raster (row, column) coordinates

21.07.2010 15:37 ·  GIS  ·  qgis, python, howto

I have noticed that recently many people have asked how to get image coordinates (row, column) from real world coordinates (latitude/longitude). The following code shows how to do this in the QGIS Python console:

import math # needed for floor() function
iface = qgis.utils.iface
# let's assume that raster is a current layer
layer = iface.mapCanvas().currentLayer()
# geographic coordinates
x = 75.0791666
y = 57.2541666
extent = layer.extent()
width = layer.width()
height = layer.height()
# raster resolution (pixel size)
xres = (extent.xMaximum() - extent.xMinimum()) / width
yres = (extent.yMaximum() - extent.yMinimum()) / height
# calculate raster coordinates (row and column)
col = int(math.floor((x - extent.xMinimum()) / xres))
row = int(math.floor((extent.yMaximum() - y) / yres))

Nothing complicated or fancy. The same code can be used in plugin with minimal changes.

⮜ Prev
Next ⮞