Wednesday, 2 May 2018

Displaying row/column of point in raster using QGIS?


Is it possible in QGIS to display column and row index of pixel in raster?


I mean something similar to value tool.



Answer



Yes, it is possible. You need to calculate the pixel coordinates in terms of row and column. For programming, it's necessary to know point coordinates and this raster information: width, height, raster units per pixel x, raster units per pixel y, xmin and ymax extent. The snipped code in a QGIS plugin to do that it could be:


.
.

.

def display_point(self, point, button):
# report map coordinates from a canvas click
coords = "{}, {}".format(point.x(), point.y())
self.dlg.lineEdit.setText(str(coords))
self.dlg.show()

layer = self.wcb.currentLayer()


if layer is not None:

width = layer.width()
height = layer.height()

xsize = layer.rasterUnitsPerPixelX()
ysize = layer.rasterUnitsPerPixelY()

extent = layer.extent()


ymax = extent.yMaximum()
xmin = extent.xMinimum()

#row in pixel coordinates
row = int(((ymax - point.y()) / ysize) + 1)

#row in pixel coordinates
column = int(((point.x() - xmin) / xsize) + 1)

if row <= 0 or column <=0 or row > height or column > width:

row = "out of extent"
column = "out of extent"

else:
row = "no raster"
column = "no raster"

self.dlg.lineEdit_2.setText(str(row))

self.dlg.lineEdit_3.setText(str(column))

.
.
.

It works well as you can see at next image:


enter image description here


If you have not experience in plugin programming, you can adapt above code to operate at Python Console of QGIS.


Without any programming, you can try this approach:


1) Get extent and raster resolution from Layer Properties.


enter image description here



2) Use this information (xinit_r, yinit_r, cell_size) at the attributes table of point vector layer (see below image). The x, y coordinates were obtained with geometry options of field calculator.


enter image description here


The values of n_row and n_column were also obtained by using the field calculator (see next images for equations):


enter image description here


enter image description here


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...