GRASS GIS logo

Note: A new GRASS GIS stable version has been released: GRASS GIS 7.8. Go directly to the new manual page here

pygrass.raster package

Submodules

pygrass.raster.abstract module

Created on Fri Aug 17 16:05:25 2012

@author: pietro

class pygrass.raster.abstract.Info(name, mapset=u'')[source]

Bases: object

bottom[source]
cols[source]
east[source]
ewres[source]
items()[source]
keys()[source]
max[source]
min[source]
mtype[source]
north[source]
nsres[source]
proj[source]
range[source]
read()[source]
rows[source]
south[source]
tbres[source]
top[source]
units
vdatum
west[source]
zone[source]
class pygrass.raster.abstract.RasterAbstractBase(name, mapset=u'', *aopen, **kwopen)[source]

Bases: object

Raster_abstract_base: The base class from which all sub-classes inherit. It does not implement any row or map access methods:

  • Implements raster metadata information access (Type, ...)
  • Implements an open method that will be overwritten by the sub-classes
  • Implements the close method that might be overwritten by sub-classes (should work for simple row access)
  • Implements get and set region methods
  • Implements color, history and category handling
  • Renaming, deletion, ...
cats_title
close(*args, **kargs)[source]

Close the map

copy_cats(*args, **kargs)[source]

Copy categories from another raster map object

exist()[source]

Return True if the map already exist, and set the mapset if were not set.

call the C function G_find_raster.

>>> ele = RasterAbstractBase(test_raster_name)
>>> ele.exist()
True
fullname()[source]

Return the full name of a raster map: name@mapset

get_cat(*args, **kargs)[source]

Return a category given an index or a label

get_cats(*args, **kargs)[source]

Return a category object

get_value(*args, **kargs)[source]

This method returns the pixel value of a given pair of coordinates:

Parameters:point – pair of coordinates in tuple object or class object with coords() method
has_cats(*args, **kargs)[source]

Return True if the raster map has categories

is_open()[source]

Return True if the map is open False otherwise.

>>> ele = RasterAbstractBase(test_raster_name)
>>> ele.is_open()
False
mode
mtype

Private method to get the Raster type

name

Private method to return the Raster name

name_mapset(name=None, mapset=None)[source]

Return the full name of the Raster.

>>> ele = RasterAbstractBase(test_raster_name)
>>> name = ele.name_mapset().split("@")
>>> name
[u'abstract_test_map']
num_cats(*args, **kargs)[source]

Return the number of categories

overwrite
read_cats(*args, **kargs)[source]

Read category from the raster map file

read_cats_rules(*args, **kargs)[source]

Read category from the raster map file

remove()[source]

Remove the map

rename(newname)[source]

Rename the map

set_cat(*args, **kargs)[source]

Set or update a category

set_cats(*args, **kargs)[source]

The internal categories are copied from this object.

set_region(region)[source]

Set the computational region that can be different from the current region settings. This region will be used by all raster map layers that are opened in the same process.

The GRASS region settings will not be modified.

set_region_from_rast(rastname=u'', mapset=u'')[source]

Set the computational region from a map, if rastername and mapset is not specify, use itself. This region will be used by all raster map layers that are opened in the same process.

The GRASS region settings will not be modified.

call C function Rast_get_cellhd, Rast_set_window

sort_cats(*args, **kargs)[source]

Sort categories order by range

write_cats(*args, **kargs)[source]

Write category to the raster map file

write_cats_rules(*args, **kargs)[source]

Write category to the raster map file

pygrass.raster.buffer module

class pygrass.raster.buffer.Buffer[source]

Bases: numpy.ndarray

shape, mtype=’FCELL’, buffer=None, offset=0, strides=None, order=None

mtype[source]

pygrass.raster.category module

Created on Thu Jun 28 17:44:14 2012

@author: pietro

class pygrass.raster.category.Category(name, mapset='', mtype='CELL', *args, **kargs)[source]

Bases: list

I would like to add the following functions:

Getting the umber of cats: Rast_number_of_cats() <- Important for ith access

Getting and setting the title: Rast_get_cats_title() Rast_set_cats_title()

Do not use these functions for category access: Rast_get_cat() and the specialized types for CELL, FCELL and DCELL. Since these functions are working on hidden static buffer.

Use the ith-get methods: Rast_get_ith_c_cat() Rast_get_ith_f_cat() Rast_get_ith_d_cat()

This can be implemented using an iterator too. So that the category object provides the [] access operator to the categories, returning a tuple (label, min, max). Using this, the category object must be aware of its raster map type.

Set categories using: Rast_set_c_cat() Rast_set_f_cat() Rast_set_d_cat()

Misc: Rast_sort_cats() Rast_copy_cats() <- This should be wrapped so that categories from an existing Python category class are copied.

copy(category)[source]

Copy from another Category class

Parameters:category (Category object) – Category class to be copied
get_cat(index)[source]
labels()[source]
mtype

Set or obtain raster data type

ncats()[source]
read()[source]

Read categories from a raster map

The category file for raster map name in mapset is read into the cats structure. If there is an error reading the category file, a diagnostic message is printed.

int Rast_read_cats(const char * name,
const char * mapset, struct Categories * pcats )
read_rules(filename, sep=':')[source]

Copy categories from a rules file, default separetor is ‘:’, the columns must be: min and/or max and label.

1:forest
2:road
3:urban

0.:0.5:forest
0.5:1.0:road
1.0:1.5:urban
Parameters:
  • filename (str) – the name of file with categories rules
  • sep (str) – the separator used to divide values and category
reset()[source]
set_cat(index, value)[source]
set_cats_fmt(fmt, m1, a1, m2, a2)[source]

Not implemented yet. void Rast_set_cats_fmt()

sort()[source]
title

Set or obtain raster title

write()[source]
Writes the category file for the raster map name in the current
mapset from the cats structure.
void Rast_write_cats(const char * name,
struct Categories * cats )
write_rules(filename, sep=':')[source]

Copy categories from a rules file, default separetor is ‘:’, the columns must be: min and/or max and label.

1:forest
2:road
3:urban

0.:0.5:forest
0.5:1.0:road
1.0:1.5:urban
Parameters:
  • filename (str) – the name of file with categories rules
  • sep (str) – the separator used to divide values and category

pygrass.raster.history module

Created on Thu Jun 28 17:44:45 2012

@author: pietro

class pygrass.raster.history.History(name, mapset='', mtype='', creator='', src1='', src2='', keyword='', date='', title='')[source]

Bases: object

History class help to manage all the metadata of a raster map

append(obj)[source]

Rast_append_history

append_fmt(fmt, *args)[source]

Rast_append_format_history

clear()[source]

Clear the history

command()[source]

Rast_command_history

creator

Set or obtain the creator of map

date

Set or obtain the date of map

format(field, fmt, *args)[source]

Rast_format_history

keyword

Set or obtain the keywords of map

length()[source]

Rast_history_length

line(line)[source]

Rast_history_line

mapset

Set or obtain the mapset of map

maptype

Set or obtain the type of map

read()[source]

Read the history of map, users need to use this function to obtain all the information of map.

>>> import grass.lib.gis as libgis
>>> import ctypes
>>> import grass.lib.raster as libraster
>>> hist = libraster.History()
short()[source]

Rast_short_history

src1

Set or obtain the first source of map

src2

Set or obtain the second source of map

title

Set or obtain the title of map

write()[source]

Rast_write_history

pygrass.raster.raster_type module

Created on Wed Jun 13 19:42:22 2012

@author: pietro

pygrass.raster.rowio module

Created on Mon Jun 18 13:22:38 2012

@author: pietro

class pygrass.raster.rowio.RowIO[source]

Bases: object

get(row_index, buf)[source]
open(fd, rows, cols, mtype)[source]
release()[source]
pygrass.raster.rowio.getmaprow_CELL(fd, buf, row, l)[source]
pygrass.raster.rowio.getmaprow_DCELL(fd, buf, row, l)[source]
pygrass.raster.rowio.getmaprow_FCELL(fd, buf, row, l)[source]

pygrass.raster.segment module

Created on Mon Jun 11 18:02:27 2012

@author: pietro

class pygrass.raster.segment.Segment(srows=64, scols=64, maxmem=100)[source]

Bases: object

close()[source]

Free memory allocated to segment and delete temp file.

cols()[source]
flush()[source]

Flush pending updates to disk. Forces all pending updates generated by Segment_put() to be written to the segment file seg. Must be called after the final Segment_put() to force all pending updates to disk. Must also be called before the first call to Segment_get_row.

format(mapobj, file_name='', fill=True)[source]

The segmentation routines require a disk file to be used for paging segments in and out of memory. This routine formats the file open for write on file descriptor fd for use as a segment file.

get(row_index, col_index)[source]

Return the value of the map

get_row(row_index, buf)[source]

Return the row using, the segment method

get_seg_number(row_index, col_index)[source]

Return the segment number

init(mapobj, file_name='')[source]
nseg()[source]
open(mapobj)[source]

Open a segment it is necessary to pass a RasterSegment object.

put(row_index, col_index)[source]

Write the value to the map

put_row(row_index, buf)[source]

Write the row using the segment method

release()[source]

Free memory allocated to segment. Releases the allocated memory associated with the segment file seg. Note: Does not close the file. Does not flush the data which may be pending from previous Segment_put() calls.

rows()[source]
segments_in_mem()[source]

Module contents

class pygrass.raster.RasterRow(name, mapset=u'', *args, **kargs)[source]

Bases: grass.pygrass.raster.abstract.RasterAbstractBase

Raster_row_access”: Inherits: “Raster_abstract_base” and implements the default row access of the Rast library.

  • Implements row access using row id
  • The get_row() method must accept a Row object as argument that will be used for value storage, so no new buffer will be allocated
  • Implements sequential writing of rows
  • Implements indexed value read only access using the [row][col] operator
  • Implements the [row] read method that returns a new Row object
  • Writing is limited using the put_row() method which accepts a Row as argument
  • No mathematical operation like __add__ and stuff for the Raster object (only for rows), since r.mapcalc is more sophisticated and faster

Examples:

>>> elev = RasterRow(test_raster_name)
>>> elev.exist()
True
>>> elev.is_open()
False
>>> elev.open()
>>> elev.is_open()
True
>>> elev.has_cats()
True
>>> elev.mode
u'r'
>>> elev.mtype
'CELL'
>>> elev.num_cats()
16
>>> elev.info.range
(11, 44)
>>> elev.info.cols
4
>>> elev.info.rows
4

Editing the history

>>> elev.hist.read()
>>> elev.hist.title = "A test map"
>>> elev.hist.write()
>>> elev.hist.title
'A test map'
>>> elev.hist.keyword
'This is a test map'
>>> attrs = list(elev.hist)
>>> attrs[0]
('name', u'Raster_test_map')
>>> attrs[2]
('mtype', '')

Each Raster map have an attribute call cats that allow user to interact with the raster categories.

>>> elev.cats          
[('A', 11, None),
 ('B', 12, None),
...
 ('P', 44, None)]
>>> elev.cats.labels() 
['A', 'B', 'C', 'D', 'E',
 'F', 'G', 'H', 'I', 'J',
 'K', 'L', 'M', 'n', 'O', 'P']
>>> elev.cats[0]
('A', 11, None)
>>> elev.cats[2]
('C', 13, None)
>>> elev.cats[0] = ('AA', 11)
>>> elev.cats[1] = ('BB', 12)
>>> elev.cats.write()
>>> elev.cats.read()
>>> elev.cats[0]
('AA', 11, None)
>>> elev.cats[1]
('BB', 12, None)

Open a raster map using the with statement:

>>> with RasterRow(test_raster_name) as elev:
...     for row in elev:
...         row
Buffer([11, 21, 31, 41], dtype=int32)
Buffer([12, 22, 32, 42], dtype=int32)
Buffer([13, 23, 33, 43], dtype=int32)
Buffer([14, 24, 34, 44], dtype=int32)
>>> elev.is_open()
False
get_row(*args, **kargs)[source]

Private method that return the row using the read mode call the Rast_get_row C function.

Parameters:
  • row (int) – the number of row to obtain
  • row_buffer (Buffer) – Buffer object instance with the right dim and type
>>> elev = RasterRow(test_raster_name)
>>> elev.open()
>>> elev[0]
Buffer([11, 21, 31, 41], dtype=int32)
>>> elev.get_row(0)
Buffer([11, 21, 31, 41], dtype=int32)
open(mode=None, mtype=None, overwrite=None)[source]

Open the raster if exist or created a new one.

Parameters:
  • mode (str) – Specify if the map will be open with read or write mode (‘r’, ‘w’)
  • type (str) – If a new map is open, specify the type of the map(CELL, FCELL, DCELL)
  • overwrite (bool) – Use this flag to set the overwrite mode of existing raster maps

if the map already exist, automatically check the type and set:

  • self.mtype

Set all the privite, attributes:

  • self._fd;
  • self._gtype
  • self._rows and self._cols
put_row(*args, **kargs)[source]

Private method to write the row sequentially.

Parameters:row (Buffer object) – a Row object to insert into raster
class pygrass.raster.RasterRowIO(name, *args, **kargs)[source]

Bases: pygrass.raster.RasterRow

Raster_row_cache_access”: The same as “Raster_row_access” but uses the ROWIO library for cached row access

close(*args, **kargs)[source]

Function to close the raster

get_row(*args, **kargs)[source]

This method returns the row using:

  • the read mode and
  • rowcache method
Parameters:
  • row (int) – the number of row to obtain
  • row_buffer – Specify the Buffer object that will be instantiate
open(mode=None, mtype=None, overwrite=False)[source]

Open the raster if exist or created a new one.

Parameters:
  • mode (str) – specify if the map will be open with read or write mode (‘r’, ‘w’)
  • type (str) – if a new map is open, specify the type of the map(CELL, FCELL, DCELL)
  • overwrite (bool) – use this flag to set the overwrite mode of existing raster maps
class pygrass.raster.RasterSegment(name, srows=64, scols=64, maxmem=100, *args, **kargs)[source]

Bases: grass.pygrass.raster.abstract.RasterAbstractBase

Raster_segment_access”: Inherits “Raster_abstract_base” and uses the segment library for cached randomly reading and writing access.

  • Implements the [row][col] operator for read and write access using Segment_get() and Segment_put() functions internally
  • Implements row read and write access with the [row] operator using Segment_get_row() Segment_put_row() internally
  • Implements the get_row() and put_row() method using Segment_get_row() Segment_put_row() internally
  • Implements the flush_segment() method
  • Implements the copying of raster maps to segments and vice verse
  • Overwrites the open and close methods
  • No mathematical operation like __add__ and stuff for the Raster object (only for rows), since r.mapcalc is more sophisticated and faster
close(*args, **kargs)[source]

Close the map, copy the segment files to the map.

Parameters:rm_temp_files (bool) – if True all the segments file will be removed
get(*args, **kargs)[source]

Return the map value using the segment.get method

Parameters:
  • row (int) – Specify the row number
  • col – Specify the column number
get_row(*args, **kargs)[source]

Return the row using the segment.get_row method

Parameters:
  • row (int) – specify the row number
  • row_buffer – specify the Buffer object that will be instantiate
map2segment(*args, **kargs)[source]

Transform an existing map to segment file.

mode

Set or obtain the opening mode of raster

open(mode=None, mtype=None, overwrite=None)[source]

Open the map, if the map already exist: determine the map type and copy the map to the segment files; else, open a new segment map.

Parameters:
  • mode (str) – specify if the map will be open with read, write or read/write mode (‘r’, ‘w’, ‘rw’)
  • mtype (str) – specify the map type, valid only for new maps: CELL, FCELL, DCELL
  • overwrite (bool) – use this flag to set the overwrite mode of existing raster maps
put(*args, **kargs)[source]

Write the value to the map using the segment.put method

Parameters:
  • row (int) – Specify the row number
  • col (int) – Specify the column number
  • val – Specify the value that will be write to the map cell
put_row(*args, **kargs)[source]

Write the row using the segment.put_row method

Parameters:row (Buffer object) – a Row object to insert into raster

Input and output must have the same type in case of row copy

>>> map_a = RasterSegment(test_raster_name)
>>> map_b = RasterSegment(test_raster_name + "_segment")
>>> map_a.open('r')
>>> map_b.open('w', mtype="CELL", overwrite=True)
>>> for row in xrange(map_a.info.rows):
...     map_b[row] = map_a[row] + 1000
>>> map_a.close()
>>> map_b.close()
>>> map_b = RasterSegment(test_raster_name + "_segment")
>>> map_b.open("r")
>>> for row in map_b:
...         row
Buffer([1011, 1021, 1031, 1041], dtype=int32)
Buffer([1012, 1022, 1032, 1042], dtype=int32)
Buffer([1013, 1023, 1033, 1043], dtype=int32)
Buffer([1014, 1024, 1034, 1044], dtype=int32)
>>> map_b.close()
segment2map(*args, **kargs)[source]

Transform the segment file to a map.

pygrass.raster.numpy2raster(array, mtype, rastname, overwrite=False)[source]

Save a numpy array to a raster map

Parameters:
  • array (obj) – a numpy array
  • mtype (obj) – the datatype of array
  • rastername (str) – the name of output map
  • overwrite (bool) – True to overwrite existing map
pygrass.raster.random_map(mapname, mtype, overwrite=True, factor=100)[source]
pygrass.raster.random_map_only_columns(mapname, mtype, overwrite=True, factor=100)[source]
pygrass.raster.raster2numpy(rastname, mapset=u'')[source]

Return a numpy array from a raster map

Parameters:rastname (str) – the name of raster map
Parar str mapset:
 the name of mapset containig raster map
pygrass.raster.raster2numpy_img(rastname, region, color=u'ARGB', array=None)[source]

Convert a raster map layer into a string with 32Bit ARGB, 24Bit RGB or 8Bit Gray little endian encoding.

Return a numpy array from a raster map of type uint8 that contains the colored map data as 32 bit ARGB, 32Bit RGB or 8 bit image
Parameters:
  • rastname (string) – The name of raster map
  • region (grass.pygrass.gis.region.Region) – The region to be used for raster map reading
  • color (String) – “ARGB”, “RGB”, “GRAY1”, “GRAY2” ARGB -> 32Bit RGB with alpha channel (0xAARRGGBB) RGB -> 32Bit RGB (0xffRRGGBB) GRAY1 -> grey scale formular: .33R+ .5G+ .17B GRAY2 -> grey scale formular: .30R+ .59G+ .11B
  • array (numpy.ndarray) –

    A numpy array (optional) to store the image, the array needs to setup as follows:

    array = np.ndarray((region.rows*region.cols*scale), np.uint8)

    scale = 4 in case of ARGB and RGB or scale = 1 in case of Gray scale

Returns:

A numpy array of size rows*cols*4 in case of ARGB, RGB and rows*cols*1 in case of gray scale

Attention: This function will change the computational raster region of the current process while running.


Note: A new GRASS GIS stable version has been released: GRASS GIS 7.8. Go directly to the new manual page here

Help Index | Topics Index | Keywords Index | Full Index

© 2003-2020 GRASS Development Team, GRASS GIS 7.4.5dev Reference Manual