3

In QGIS I am trying to read raster band data from a specific layer in my Python plug in.

I can easily get access to the layer from the console with something like this.

iface.mapCanvas().layers()[0]

and I can easily get access to a single random pixel value with something like this.

iface.mapCanvas().layers()[0].dataProvider().sample(QgsPointXY(longitude, <latitude>),1)

but what I want to do is grab the whole band matrix of values. something akin to this.

ds = gdal.Open(iface.mapCanvas().layers()[0].source()) 
band1 = np.array(ds.GetRasterBand(1).ReadAsArray())

but without having to open up the file again.

I assume since the band data is attached to the layer that I must be able to access it somehow, but I've now spent hours reading documentation trying to figure it out only to come up short.

Is there a way to read band data from a raster layer into a numpy array in pyQGIS once I get access to the layer I care about? or is the "open a file using the layer source with GDAL" my best option?

  • 1
    did my solution work for you @Semicolons and Duct Tape? If so, please click the green mark to show others this is an accepted solution – 15Step Aug 6 at 17:16
2

Here is a function to convert a QgsRasterLayer to a numpy array without GDAL through using the block method of the QgsRasterDataProvider(link):

from numpy import array

def convertRasterToNumpyArray(lyr): #Input: QgsRasterLayer
    values=[]
    provider= lyr.dataProvider()
    block = provider.block(1,lyr.extent(),lyr.width(),lyr.height())
    for i in range(lyr.width()):
        for j in range(lyr.height()):
            values.append(block.value(i,j))
    return array(values)

lyr = iface.mapCanvas().layers()[0]

print(convertRasterToNumpyArray(lyr))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.