Select to view content in your preferred language

Raster calculator python script

1370
2
05-22-2014 02:58 AM
Leo_KrisPalao
Emerging Contributor
Hi ArcGIS Users,

Good Day!

I am processing raster data and would want to use raster calculator to compute values for my rasters. Basically, what I want to do is -- I have a set of raster data in one folder and I want to divide each raster with a unique value. Example is:

( Raster 1 / 9.2 ) * 100
( Raster 2 / 15.2 ) * 100
.
.
.
.
.
( Raster 37 / 12.5 ) * 100

I have been searching for an appropriate method on how to do this in python. Could you point me in the right direction (i.e., blog or website) or can somebody from the forum help me how to get started.

Thanks in advance for your help,
-Leo
Tags (2)
0 Kudos
2 Replies
ChrisSnyder
Honored Contributor
How are the unique values derived fro each raster? Are they a function of the raster itself (like the mean pixel value) or is it just some arbitrary number?

If it's the latter, here's one (untested) possible solution:

rasterValDict = {"raster1": 11.2, "raster2": 14.9, ..., "raster_37": 9.4}
rasterDirPath = r"C:\temp\where_my_rasters_are"
outputDirPath = r"C:\temp\output_dir"
arcpy.env.workspace = rasterDirPath
rasterList = arcpy.ListRasters()
for raster in rasterList:
   rasterObj = arcpy.Raster(raster)
   if raster in rasterValDict: 
      newRaster = rasterObj / rasterValDict[raster] * 100
      newRaster.save(outputDirPath + "\\" + raster)
   else:
      print "ERROR: No matching entry in raster value look up dictionary!"
0 Kudos
Leo_KrisPalao
Emerging Contributor
Hi Chris,

I already ran the code that you shared with me. I tested the code with only five rasters. When I ran the code it says:

>>> ERROR: No matching entry in raster value look up dictionary!
ERROR: No matching entry in raster value look up dictionary!
ERROR: No matching entry in raster value look up dictionary!
ERROR: No matching entry in raster value look up dictionary!
ERROR: No matching entry in raster value look up dictionary!

I checked each variable in code and it is okay, except for newRaster. When I enter the command >>> print newRaster it says NameError: name 'newRaster' is not defined

Below is the code that you gave me. Sorry for this, I am still learning how to write python codes. And it is a steep learning curve for me.

Thanks,
-Leo

import arcpy, os
rasterValDict = {"raster1": 11.2, "raster2": 14.9, "raster3": 9.4, "raster4": 9.4, "raster5": 9.4}
rasterDirPath = r'E:\Test\Criteria'
outputDirPath = r'E:\Test\rastercalc'
arcpy.env.workspace = rasterDirPath
rasterList = arcpy.ListRasters()
for raster in rasterList:
   rasterObj = arcpy.Raster(raster)
   if raster in rasterValDict: 
      newRaster = rasterObj / rasterValDict[raster] * 100
      newRaster.save(outputDirPath + "\\" + raster)
   else:
      print "ERROR: No matching entry in raster value look up dictionary!"
0 Kudos