Python For循环中的ArcGIS Raster Calculator错误

时间:2016-08-25 13:45:59

标签: python for-loop arcgis raster

我正在通过python在ArcGIS计算器中执行一个简单的for循环。我想使用从第一年(r2005)到第二年(r2009)的封面类生成过渡图。这是代码:

# Importing libraries

import arcpy, sys, string, os, arcgisscripting, dircache
import numpy as np
from arcpy import env
from arcpy.sa import *

# Creating the geoprocessor object
gp = arcgisscripting.create()

# Setting environment
arcpy.env.compression = "LZW"

# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")

# Reading data
classes = np.genfromtxt("Globcover_Legend_Neotropics.txt", dtype="int")
r2005 = Raster("2005_Clip.tif")
r2009 = Raster("2009_Clip.tif")

# Creating transition rasters
for i in classes:
    for j in classes:       
        #OPTION1
        #outEqualTo1 = r2005==i
        #outEqualTo2 = r2009==j
        #transition_raster = (outEqualTo1) & (outEqualTo2)
        #OPTION2
        transition_raster = (r2005 == i) & (r2009 == j)
        transition_raster.save(str(i)+"_"+str(j)+".tif")
        print (str(i)+"_"+str(j))

对象“classes”是一个包含要比较的封面类的numpy数组:

>>> classes
array([ 14,  20,  30,  40,  50,  60,  70, 100, 110, 120, 130, 140, 150,
       160, 170, 180, 190, 200, 210, 220])

当我使用循环中的任何元素运行代码时,它运行完美。例如:

>>> i=j=14
>>> transition_raster = (r2005 == i) & (r2009 == j)
>>> transition_raster.save(str(i)+"_"+str(j)+".tif")

但是,当我运行完整的for循环时,我收到此错误:

Traceback (most recent call last):
  File "D:\Cover\GlobCover\transitions.py", line 31, in <module>
    transition_raster = (r2005 == i) & (r2009 == j)
  File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\sa\Functions.py", line 3831, in EqualTo
    in_raster_or_constant2)
  File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\sa\Utils.py", line 47, in swapper
    result = wrapper(*args, **kwargs)
  File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\sa\Functions.py", line 3828, in Wrapper
    ["EqualTo", in_raster_or_constant1, in_raster_or_constant2])
TypeError: expected a raster or layer name

我尝试了代码中的两个选项(参见代码),我得到了同样的错误。有什么想法吗?在此先感谢并欢呼!

1 个答案:

答案 0 :(得分:0)

您知道值14有效,但无论TypeError返回的循环是什么,您都会获得classes14的类型为int,因此在进行比较之前,请尝试将ij类型转换为int

for i in classes:
    for j in classes:
        transition_raster = ( (r2005 == int(i)) & (r2009 == int(j)) )
        # added typecasts:              ^^^^ ^              ^^^^ ^
        ...