Last active
May 28, 2024 14:58
-
-
Save deppen8/319f30ec31011ab6a649b1d147606138 to your computer and use it in GitHub Desktop.
Get pixel coordinates on-click in QGIS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Get pixel coordinates (not geographic coordinates) of a location in a raster. | |
Run the script to activate the tool. | |
Click a location to see row, column printed to Python console. | |
Click any other tool to deactivate. | |
Original source: https://gis.stackexchange.com/a/261538/67365 | |
Modified slightly from the original for compatibility with Python 3 + QGIS 3 - Hannover | |
""" | |
from qgis.gui import QgsMapTool | |
from PyQt5.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(f"{row}, {col}") | |
tool = ClickTool(iface.mapCanvas()) | |
iface.mapCanvas().setMapTool(tool) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment