Unit 13 - PyGRASS intro

PyGRASS has been design as an object-oriented Python API to GRASS. This is a major difference to GRASS Scripting Library which consists of procedures - Python functions. It is important to mention that PyGRASS has not been designed as replacement of GRASS Scripting Library, the both libraries are living next to each other. It is up to the user (you) which library use in his/her scripts. It’s also possible to compine the both libraries in one script.

We open raster map as Python object by RasterRow.

from grass.pygrass import raster
ndvi = raster.RasterRow('ndvi')

Raster map will be open by open() method, basic information like number of columns and rows, min and max value, range printed.

print (ndvi.info.cols, ndvi.info.rows)
min, max = ndvi.info.range
print (min, max)
print (max-min)

Fig. 84 Running PyGRASS code in Python tab of Layer Manager.

Don’t forget to close the raster map.


In next part we create a simple PyGRASS script for computing basic univariate raster statistics.

#!/usr/bin/env python

import numpy as np
from grass.pygrass import raster

ndvi = raster.RasterRow('ndvi')

min = max = None
count = ncount = 0
for row in ndvi:
    for value in row:
        if np.isnan(value):
            ncount += 1
            if min is None:
                min = max = value
                if min > value:
                    min = value
                elif max < value:
                    max = value
        count += 1


print ("min={0:.6f} max={1:.6f} count={2} (no-data: {3})".format(
    min, max, count, ncount)


Compare computation speed of your simple script with r.univar module.

Sample script to download: ndvi-pygrass-univar.py