4

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?

0

2 Answers 2

1

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.height()):
        for j in range(lyr.width()):
            values.append(block.value(i,j))
    return array(values)

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

print(convertRasterToNumpyArray(lyr))
0
0

Reading data by nested loop is not necessary. Numpy (like other languages) has the utility to read memory buffer directly:

The only problem is to use proper data type:

rast = iface.mapCanvas().layers()[0]
prov = rast.dataProvider()
block = prov.block(1,rast.extent(),rast.width(),rast.height())
data = np.frombuffer(block.data(),dtype=np.uint8)# set proper data type
data.shape=(rast.height(),rast.width()) # opposite to raster
1
  • This question is almost 5 years old and I'm not using QGIS anymore so I can't confirm it, but this is much more like the solution I was looking for at the time. If someone else can can confirm it works or if @jarekj71 can post a more detailed screen shot of it working ... happy to at least upvote. Jan 4 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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