PyQGIS: Get Raster Data with GDAL


PyQGIS has some methods for accessing single values in a raster, but the best way to access raster data is using the Geospatial Data Abstraction Library, or GDAL. GDAL comes pre-installed on the QGIS Python interpreter, so if you access the Python interpreter from QGIS (Plugins > Python Console) you won’t have to install any packages.

First, import GDAL.

from osgeo import gdal

Next you need to get information for the layer you want to work with. The code below gets the layer information for the first layer in the Table of Contents named ‘layer name’.

layers = QgsProject.instance().mapLayersByName('layer name')
layer = layers[0]

Now you can get the file name of the layer and open that file name as a GDAL datasource.

ds = gdal.Open(layer.dataProvider().dataSourceUri())

Once you have created the GDAL datasource, you can select a raster band and read the data from that raster band as a 2D numpy array.

dem_arr = ds.GetRasterBand(1).ReadAsArray()

Now you can access data from the array with numpy indexing. The code below prints the value of the raster band in the first row and first column.

print(dem_arr[0][0])

Here is what the final code block should look like. Watch the video below for a step by step demonstration of the process.

from osgeo import gdal
layers = QgsProject.instance().mapLayersByName('layer name')
layer = layers[0]
ds = gdal.Open(layer.dataProvider().dataSourceUri())
dem_arr = ds.GetRasterBand(1).ReadAsArray()
print(dem_arr[0][0])

Konrad Hafen

Konrad is a natural resources scientist. He develops models and analysis workflows to predict and evaluate changes to landscapes and water resources.

Latest Tutorials