For Loop - Map Algebra (ArcGIS) using Python
In the line Temp4 = FocalStatistics('RasterImage', NbrRectangle (9, 9, 'CELL'), "RANGE", "DATA")
, you need to remove the single-quotes around RasterImage
-- it is being treated as a string literal and looking for a file called RasterImage.
Edit: Thinking about this some more, I'm wondering if the script is failing because you initialize Temp4 as a string but then redefine it as whatever the return type of FocalStatistics is -- I'm not sure if it's handled as a string or not.
Try this:
import arcpy, os, sys, string
from arcpy import env
from arcpy.sa import *
arcpy.CheckOutExtension("spatial")
arcpy.env.workspace = r'O:\DATA\test'
InputFolder = arcpy.env.workspace
def focalStats(raster):
Temp4 = FocalStatistics(raster, NbrRectangle(9, 9, 'CELL'), "RANGE", "DATA")
return Temp4
RasterList = arcpy.ListRasters()
for RasterImage in RasterList:
print (RasterImage)
focalStats(RasterImage)
print ('Focal Statistics Done')
As @nmpeterson says, the first issue comes down to the quotes around the RasterImage
variable name.
However the big thing is that you are overwriting the variable Temp4 with the contents of the raster. Instead, according to the FocalStatistics documentation from ESRI, the raster object returned has a save(path)
method.
I'm assuming you don't want to overwrite your output each time, so one quick way of getting a temporary name is in Python using tempfile.NamedTemporaryFile(dir="working_dir").name
- however this won't store a reference to the original Raster, which I'll assume you want, so we can do it slightly differently as follows (assuming you're using Info rasters - if you're using a .tif, .png etc you'll have to strip the file extension before creating the new file):
import arcpy, os, sys, string
from arcpy import env
from arcpy.sa import *
arcpy.CheckOutExtension("spatial")
input_folder = r'O:\DATA\test'
arcpy.env.workspace = input_folder
raster_list = arcpy.ListRasters()
for raster_image in raster_list:
print (raster_image)
f_stats = FocalStatistics(raster_image, NbrRectangle(9, 9, 'CELL'), "RANGE", "DATA")
f_stats_out = input_folder + os.sep + raster_image + "_f_stats.tif"
f_stats.save(f_stats_out)
print ('Focal Statistics Done')
One final time - standard Python convention is to use lower case for variable names with underscores (see PEP 8) but in the end it's not a big thing.