So far, we have dealt only with vector layers. It’s time to look into raster basics!

Loading a raster layer is very similar to loading a vector layer. Instead of addVectorLayer(), we use addRasterLayer() and the provider parameter changes from “ogr” to “gdal”:

uri = "E:/Geodata/qgis_sample_data/raster/SR_50M_alaska_nad.tif"
rlayer = iface.addRasterLayer(uri,"my raster","gdal")

if rlayer.isValid():
    print("This is a valid raster layer!")
else:
    print("This raster layer is invalid!")

Both QgsRasterLayer and QgsVectorLayer objects have an isValid() function. It can be used to check if the layer could be loaded correctly. In the above example, we check if the raster layer is valid and – depending on the results – we print a corresponding message. This is the first time we use an if statement. Like with the for loops we used earlier, if statements are followed by a colon and the code that should be executed if the condition holds is indented. If statements are a very common tool to control the behavior of your scripts.

If the raster is valid, we can get some information about it:

print("Width: {}px".format(rlayer.width()))
print("Height: {}px".format(rlayer.height()))
print("Extent: {}".format(rlayer.extent().toString()))

We’ve used string formatting before. It’s a good way to format script output. Note how we used rlayer.extent().toString() instead of just rlayer.extent(). Without calling toString(), the output would be something like:
Extent: <qgis._core.QgsRectangle object at 0x0000028CDA596E58>
which tells us that rlayer.extent() returns a QgsRectangle object but does not tell us the actual layer extent.

Besides checking the raster size and extent, another common task is to get the raster pixel values. To get the minimum and maximum values of a single-band raster, we can access its data provider’s band statistics:

stats = rlayer.dataProvider().bandStatistics(1)
print("Min value: {}".format(stats.minimumValue))
print("Max value: {}".format(stats.maximumValue))

bandStatistics(1) returns a QgsRasterBandStats object for the first (and in our case only) raster band. This object provides access to a couple of statistics beyond min and max. Go check it out in the official docs!

These are the basics of working with raster layers. You also saw how to use if statements to check whether a certain condition is fulfilled or not.

Next


PyQGIS 101 is a work in progress. I’d appreciate any feedback, particularly from beginners!

2 comments
  1. Chandan Kumar Singh said:

    How to add and analyse multiple Raster layer using PyQGIS?

  2. GeekinHell said:

    stats.minimumValue and stats.maximumValue gives me 1 and 128. But, the minimum and maximum value of the raster I added is 1 and 23. Why am I getting different values?

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.