Unit 13 - PyGRASS Data Access

PyGRASS allows directly accessing native GRASS raster and vector maps in the sense of Python objects. This unit shows how to deal with GRASS data by PyGRASS API.

Raster data

Raster map can be treated by RasterRow for reading raster data row by row. There is also RasterSegment which allows reading data by user-defined segments (tiles).

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

Raster map is open by open() method. Basic information like number of columns and rows, min and max values, range printed.

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

Fig. 85 Running PyGRASS code from Python tab of Layer Manager.

Don’t forget to close the raster map at the end.


Vector data

Vector map can be treated by Vector when dealing with basic vector primitives (points, lines, boundaries, centroids) or by VectorTopo which allows accessing topological primitives like areas or isles. See Vector topology section for details.

Example below prints nicely format region names and their area size in hectares.

from grass.pygrass.vector import VectorTopo
fylke = VectorTopo('Fylke')

for feat in fylke.viter('areas'):
    print (u'{0}: {1:.1f}ha'.format(feat.attrs['navn'].split(':', 1)[1][:-1], feat.area() / 10e4))


Fig. 86 PyGRASS vector example in action.

Raster statistics example

A simple PyGRASS script for computing basic univariate raster statistics below.

#!/usr/bin/env python

import numpy as np
from grass.pygrass.raster import RasterRow

ndvi = 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 C-based r.univar module…


Fig. 87 PyGRASS script and r.univar comparision.

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