[GRASS-user] Python Script for changing raster values

Greetings

I have a classification raster (with values that ranges from 1-20) and I need to reclassify them. I mean, to change (as an example):
1- > 255
2- > 100
3 → 150

and I need to implement this on a Python script. What do you suggest to do? I mean, that is the most robust and easy way to implement this?
Thanks
Luisa

Following code could be one approach:

os.system(“cat %s | r.recode input=map_a output=map_recl” % path_to_rules)

where path_to_rules is a previously created (temp) file containg the reclassifiying rules as for example:

1:1:1.1:1.1
2:2:7.5:7.5
3:3:0.4:0.4

Christian.

From: Luisa Peña
Sent: Tuesday, September 07, 2010 12:37 PM
To: GRASS user list
Subject: [GRASS-user] Python Script for changing raster values

Greetings

I have a classification raster (with values that ranges from 1-20) and I need to reclassify them. I mean, to change (as an example):
1- > 255
2- > 100
3 → 150

and I need to implement this on a Python script. What do you suggest to do? I mean, that is the most robust and easy way to implement this?
Thanks
Luisa



grass-user mailing list
grass-user@lists.osgeo.org
http://lists.osgeo.org/mailman/listinfo/grass-user

Christian Schwartze wrote:

Following code could be one approach:

os.system("cat %s | r.recode input=map_a output=map_recl" % path_to_rules)

where path_to_rules is a previously created (temp) file containg the
reclassifiying rules as for example:

os.system() shouldn't be used. E.g. the above will fail if
path_to_rules contains spaces (as is often the case on Windows).

The preferred approach for the above command is:

  grass.run_command("r.recode", input="map_a",
      output="map_recl", rules = path_to_rules)

If you have a command which requires input via stdin (rather from a
named file), use e.g.:

  rules_f = open(path_to_rules, "r")
  try:
      grass.run_command("r.recode", input="map_a",
          output="map_recl", stdin = rules_f)
  finally:
      rules_f.close()

Or, if you can rely upon Python 2.5 or later, use:

  from __future__ import with_statement
  with open(path_to_rules, "r") as rules_f:
      grass.run_command("r.recode", input="map_a",
          output="map_recl", stdin = rules_f)

Also, even in shell scripts "cat file | command" is suboptimal; use
"command < file" instead.

--
Glynn Clements <glynn@gclements.plus.com>