自定义python函数将无法识别已定义的变量

问题描述 投票:-1回答:1

我不熟悉编写函数(使用IDLE作为我选择的IDE),并且我试图编写一个函数,该函数将获取LANDSAT 8卫星图像并计算NDVI图像。如果您不熟悉LANDSAT 8卫星,它将收集多个波段,这些波段可以组合为NDVI等指标。该函数如下所示,并保存为ndviCalc2.py:

def ndvi(var1, var2):
    var1 = floatNir
    var2 = floatRed
    num = Minus(floatNir, floatRed)
    denom = Plus(floatNir, floatRed)
    ndvi = Divide(num, denom)

我正在尝试在以下脚本中调用该函数:

#Import required python modules
import arcpy
import sys

#Update directory to import custom python modules, where the calcNdvi2.py file is saved
sys.path.append("C:\\Users\\Documents")

#Import custom function
import ndviCalc2

#Import classes: env specifies the workspace environment, and arcpy.sa specifies an extension that must be activated to run the script
from arcpy import env
from arcpy.sa import *

#Check out spatial extension
arcpy.CheckOutExtension("Spatial")

#Set environments
env.workspace = "C:\\Users\\Documents\\toolData"
env.overwriteOutput = True

#Define local parameters, including different bands from the satellite image
input = "LANDSAT8_20150609.tif"
nir = input + "\\Band_5"
red = input + "\\Band_4"

#Convert parameters to floatin point rasters for calculation
floatNir = Float(nir)
floatRed = Float(red)

#Use custom script to calculate NDVI
#Calling the custom function here, and error occurs here:
ndvi = ndviCalc2.ndvi(floatNir, floatRed)

#Save raster to the workspace
ndvi.save(env.workspace + "\\ndvi_image.tif")

#Check spatial extension back in
arcpy.CheckInExtension("Spatial")

我收到以下错误消息:

Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    ndvi = calcNdvi_correct.ndvi(floatNir, floatRed)
  File "C:\Users\Documents\ndviCalc2.py", line 11, in ndvi
    var1 = floatNir
NameError: global name 'floatNir' is not defined

如何重写并正确调用函数以使其正常执行?

python function spatial arcpy
1个回答
1
投票
def ndvi(floatNir, floatRed):
    num = Minus(floatNir, floatRed)
    denom = Plus(floatNir, floatRed)
    ndvi = Divide(num, denom)

这应该是您的函数定义。如果要传递floatNir和floatRed,则无需使用其他变量。

© www.soinside.com 2019 - 2024. All rights reserved.