Given a rectified image, that is an image without rotation, or a regular raster, you may paste the following scripts into the Python console or execute them as script from the editor. Each of them outputs row and columns indices (0..x/y).
The first script is based on class QgsMapTool implementing canvasPressEvent()
method. It evaluates clicks with the left mouse button. Once executed the tool remains active until another map tool is activated.
For more details see this answer.
from qgis.gui import QgsMapTool
from PyQt4.QtCore import Qt, QPoint
from math import floor
# references to QGIS objects
canvas = iface.mapCanvas()
layer = iface.activeLayer()
data_provider = layer.dataProvider()
# properties to map mouse position to row/col index of the raster in memory
extent = data_provider.extent()
width = data_provider.xSize() if data_provider.capabilities() & data_provider.Size else 1000
height = data_provider.ySize() if data_provider.capabilities() & data_provider.Size else 1000
xres = extent.width() / width
yres = extent.height() / height
class ClickTool(QgsMapTool):
def __init__(self, canvas):
QgsMapTool.__init__(self, canvas)
self.canvas = canvas
def canvasPressEvent(self, event):
if event.button() == Qt.LeftButton:
x = event.pos().x()
y = event.pos().y()
# clicked position on screen to map coordinates
point = self.canvas.getCoordinateTransform().toMapCoordinates(x, y)
if extent.xMinimum() <= point.x() <= extent.xMaximum() and \
extent.yMinimum() <= point.y() <= extent.yMaximum():
col = int(floor((point.x() - extent.xMinimum()) / xres))
row = int(floor((extent.yMaximum() - point.y()) / yres))
print row, col
tool = ClickTool(iface.mapCanvas())
iface.mapCanvas().setMapTool(tool)
The second script will output the row and column index of the raster below the current cursor position, and is updated while the cursor is moving. When the cursor is outside the extend of the raster, then nothing is printed.
from math import floor
# references to QGIS objects
canvas = iface.mapCanvas()
layer = iface.activeLayer()
data_provider = layer.dataProvider()
# properties to map mouse position to row/col index of the raster in memory
extent = data_provider.extent()
width = data_provider.xSize() if data_provider.capabilities() & data_provider.Size else 1000
height = data_provider.ySize() if data_provider.capabilities() & data_provider.Size else 1000
xres = extent.width() / width
yres = extent.height() / height
# slot called whenever mouse position changes
def show_raster_row_col(point):
if extent.xMinimum() <= point.x() <= extent.xMaximum() and \
extent.yMinimum() <= point.y() <= extent.yMaximum():
col = int(floor((point.x() - extent.xMinimum()) / xres))
row = int(floor((extent.yMaximum() - point.y()) / yres))
# output row and column index to console
print row, col
# connect slot to canvas signal
canvas.xyCoordinates.connect(show_raster_row_col)
To stop the script, type the following line into the console:
canvas.xyCoordinates.disconnect(show_raster_row_col)