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.

ndvi.open()
print (ndvi.info.cols, ndvi.info.rows)
min, max = ndvi.info.range
print (min, max)
print (max - min)
../_images/pygrass-shell.png

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

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

ndvi.close()

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')
fylke.open('r')

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

fylke.close()
../_images/pygrass-shell-vector.png

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')
ndvi.open()

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

ndvi.close()

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

Tip

Compare computation speed of your simple script with C-based r.univar module…

../_images/r-univar.png

Fig. 87 PyGRASS script and r.univar comparision.

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