I'm working in the Python-Console of QGIS and I have an object form the class QgsRasterLayer
. I want to get the indices of those pixels that have certain pixel value (e.g. I need the indices of all the pixels with a pixel value = 50), but I don't know how.
1 Answer
This script should work:
# lyr = iface.mapCanvas().currentLayer() # You don't need this if you already have a QgsRasterLayer
prov = lyr.dataProvider()
extent = prov.extent()
width = prov.xSize()
height = prov.ySize()
block = prov.block(1, extent, width, height)
for x in range(width):
for y in range(height):
val = block.value(y, x)
if val == 50:
print x, y
Note that this gives you the indices of the pixels, and not their geographic coordinates.
-
Thank you a lot ArMoraer!! Instead "xSize" and "ySize" for me only lyr.width() and lyr.height() worked. But I got a problem in the 'block' line. I tried these: block = lyr.dataProvider().block(1, lyr.extent(), lyr.width(), lyr.height())--> But I get this error: "AttributeError: 'QgsRasterDataProvider' object has no attribute 'block'". Infortunately I'm working with the python console in a very old version of QGIS (Lisboa-1.8) because I'm at work and for specific reasons they don't want to move to a recent QGIS version. Can that be the reason why 'block' does not work for me?– Diego FGCommented Jun 7, 2016 at 14:58
-
From QGIS 1.8 API doc, it seems that you can use
readBlock()
instead. I can't really test it though, so I hope it will work...– ArMoraerCommented Jun 7, 2016 at 21:18 -
Unfortunately I got the same error with
readBlock()
. I finally managed to get the indices by creating a numpy array from the raster and then using the functionnp.where(raster==50)
. But thank you a lot @ArMoraer, a block seems a pretty straightforward solution, unfortunately not in the version I'm using– Diego FGCommented Jun 8, 2016 at 13:37