Thursday 12 January 2017

spatial analyst - Adding two rasters using map algebra in ArcPy?


I want to simply add two rasters within a python script using map algebra, which from what I understand is the equivalent to adding two rasters in the raster calculator.


If I do this using raster calculator and simply type "Raster1 + Raster2", it works perfectly. However, if I run this in a python script, I get error000732: Input Raster: Dataset Raster1 does not exist or is not supported.


Here is my code:


import arcpy
from arcpy import env
from arcpy.sa import *
raster1 = ("C:/raster1")
raster2 = ("C:/raster2")

raster3 = Raster("raster1") + Raster("raster2")

I set up the syntax based on the Esri help page for Map Algebra http://desktop.arcgis.com/en/arcmap/latest/extensions/spatial-analyst/map-algebra/an-overview-of-the-rules-for-map-algebra.htm


I'm not sure why my rasters are recognized within the raster calculator but not map algebra.



Answer



What @Joseph says. The Raster class needs a string containing the path to your raster. You've correctly assigned this to a variable, so you then need to pass those variables to instantiate your Rasters. This code should work:


import arcpy
from arcpy import env
from arcpy.sa import *
raster1 = ("C:/raster1")

raster2 = ("C:/raster2")

#Note lack of quotes in following line
raster3 = Raster(raster1) + Raster(raster2)

#Don't forget to save eg:
raster3.save("C:/raster3")

The reason the documentation you link shows the rasters being passed to map algebra statements in quotes is because they assume you are typing in the python console in ArcMap. If you're raster datasets are open in ArcMap you can refer to them by their name in the table of contents, using quotes.


In which case the necessary code would be



import arcpy
from arcpy import env
from arcpy.sa import *

#No need to assign paths to variables.
#NB You still need to call `Raster()` in order to tell Arcpy that the '+' is for raster math.
raster3 = Raster("raster1") + Raster("raster2")

#Don't forget to save eg:
raster3.save("C:/raster3")

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...