[GRASS-dev] casting row buffer in memory

Pietro peter.zamb at gmail.com
Mon Oct 6 05:54:38 PDT 2014

Trying to circumvent the r.mapcalc min/max limit, I found out another
problem when I'm trying to cast a buffer from one type to another.

The code is:

from __future__ import print_function
import numpy as np

from grass.pygrass.raster import RasterRow
from grass.pygrass.messages import get_msgr

def scale(mn, mx, newmn=0, newmx=1, dtype=np.float32):
    print("from (%r, %r) to (%r, %r): %r" % (mn, mx, newmn, newmx, dtype))
    def do(row):
        return dtype((row - mn) / (mx - mn) * (newmx - newmn) + newmn)
    return do

def rescale(input, output, new_min=0, new_max=255, mtype='CELL'):
    dtype = np.int32 if mtype == 'CELL' else np.float32 if mtype ==
'FCELL' else np.float64
    msgr = get_msgr()
    with RasterRow(input, mode='r') as inp:
        scaler = scale(inp.info.min, inp.info.max, new_min, new_max, dtype)
        with RasterRow(output, mode='w', mtype=mtype, overwrite=True) as out:
            binp = inp[0]
            rows = inp._rows
            for i in range(rows):
                msgr.percent(i, rows, 1)
                out.put_row(scaler(inp.get_row(i, binp)))

rescale('el', 'cel255', 0, 255, mtype='CELL')
rescale('el', 'fel255', 0, 255, mtype='FCELL')
rescale('el', 'del255', 0, 255, mtype='DCELL')

and these are the results

$ python2 cmd.py
from (0.3555224724894053, 0.9999997729286152) to (0, 255): <type 'numpy.int32'>
from (0.3555224724894053, 0.9999997729286152) to (0, 255): <type
from (0.3555224724894053, 0.9999997729286152) to (0, 255): <type

$ r.info cel255
    Range of data:    min = -2147483405  max = 2147176055

$ r.info fel255
    Range of data:    min = -3.402784e+38  max = 3.402818e+38

$ r.info del255
     Range of data:    min = 0  max = 255

So even if I'm explicitly casting the result in the scaler function
with dtype(...), the result is not properly casted, do you have an
idea on how could I solve this problem?

All the best


More information about the grass-dev mailing list