I wrote a small Python Toolbox (.pyt) file to calculate an output raster based on some input raster layers.
Now I want to include the option to either save the output to a file, or to create a temporary raster layer. In both cases, I would like the option to display the output in the current project after the calculations are finished.
I tried to save with "in_memory" or "memory" as the output path, but this only created some file with that name in the current GeoDataBase. When I use no path instead (i.e., use the code in the final if/or statement of the code), I suppose the file is created but I do not know where it ends up. If in this case the file is created in memory, I need some help adding the file to the map.
This is the code I used (indentation might be messed up due to copy pasting here):
# -*- coding: utf-8 -*-
import arcpy, os
from arcpy.sa import Raster
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "Spectral_indices"
self.alias = "specindic"
# List of tool classes associated with this toolbox
self.tools = [Calculate_NDVI]
class Calculate_NDVI(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "NDVI"
self.description = "Calculate normalized difference vegetation index (NDVI) from raster layers."
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
RED = arcpy.Parameter(
displayName="Red layer",
name="red",
datatype="DERasterBand",
parameterType="Required",
direction="Input")
NIR = arcpy.Parameter(
displayName="Near infrared (NIR) layer",
name="nir",
datatype="DERasterBand",
parameterType="Required",
direction="Input")
OUT_DIR = arcpy.Parameter(
displayName="Output directory",
name="dir",
datatype="GPRasterLayer",
parameterType="Optional",
direction="Output")
parameters = [RED, NIR, OUT_DIR]
return parameters
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
RED = parameters[0].valueAsText
NIR = parameters[1].valueAsText
NDVI = (Raster(NIR) - Raster(RED)) / (Raster(NIR) + Raster(RED))
OUT_DIR = parameters[2].valueAsText
if OUT_DIR is None:
arcpy.env.workspace = "memory"
OUT_DIR = arcpy.CreateUniqueName("NDVI.tif")
NDVI.save(OUT_DIR)
return
formatting and line numbers
Code formatting ... the Community Version - Esri Community
Fixed it. I didn't know about this hidden feature...
Hi, Manu.
Did you solve how to save the temporal output raster? I have the same question.