pycharm在arcpy开发中arcgis工具箱打包
明天就国庆了,刚好最近在使用python在arcgis方面批处理开发工作,写了一些总结,以备后用。
这次我们先做了一个测试工具,其主要目的是利用toolbox工具箱的Mosaic To New Raster将多个栅格数据合成一个栅格数据。如果说栅格数量少的话,手动选择并没有太大的影响。而如果栅格文件非常多的话,手动选择将浪费大量的时间和精力,为此我们写了一个小工具,将某个目录下所有的栅格数据一次性加入到上面的Mosaic To New Raster工具中,直接运行即可。说得直接一点就是直接调用了Mosaic To New Raster工具,一次性加入多个文件。在写完这个工具后遇到工具打包和工具多个参数类型问题,现将自己写这部分功能中遇到的问题特记录下来。
利用python调用arcpy脚本后,如果使用代码的方式让用户使用编写的脚本是极其的不方便和友好。为此,需要利用某种方式将写好的脚本代码封装成类似arcgis中工具箱的工具。解决方案是,将写好的代码的目录利用catalog将其添加到arcgis中,然后在arcgis中选择该目录,右击选择【New】、选择【Python ToolBox】。这样在该目录下就生成了Toolbox.pyt文件。具体操作如下图所示。
接下来利用pycharm再次将刚才的目录导入,也可以不用该步骤。如下图所示,可以看到有新生成的三个文件。如果pyt后缀的文件在pycharm中为灰色,那么说明该后缀的pyt的python代码没有被pycharm所识别,如何解决这个问题,可以参考之前写的博客pycharm导入.pyt后缀文件
首先我们在单独文件python文件中,写了我们功能函数,而我们现在需要配置参数,将我们需要的参数传入到具体的功能函数中。具体来说就是做成类似下面的将多个数据源文件合并成新的一个文件。每个输入框对应这我们功能函数的一个参数。
函数中,添加如下代码对应的参数。注意每个参数都有displayName、name、dataType、paramterType、direction参数,分别代表这在工具框显示名称,对应名称,数据类型、参数类型、方式(必须还是可选)。在这里我们利用到dataType数据类型有Folder(目录)、GPString(字符)、Long(长形数据)、GPSpatialReference(空间参考)、同时有选项还会出现是选择框类型,可以对参数的属性设置filter.type=”ValueList”、对应列举相应的值,如filter.list=[“11”,”22”,”33”]、设置选择框的默认选择值可利用参数的value属性,具体参数可以参考代码。最后做成如下的结果界面。是不是感觉和Mosaic To New Raster工具非常像。
在ToolBox.pyt,弹出框配置输入参数代码如下:
# coding:gbk
import arcpy
from MosaicToNewRaster import doExcute
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "Toolbox"
self.alias = ""
# List of tool classes associated with this toolbox
self.tools = [Tool]
class Tool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "批量合成某一目录下所有的tif"
self.description = "批量合成某一目录下所有的tif"
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
dataFolder=arcpy.Parameter(
displayName="数据文件夹",
name="dataFolder",
datatype="Folder",
parameterType="Required",
direction="Input"
)
exTension=arcpy.Parameter(
displayName="数据集名称以及扩展名",
name="exTension",
datatype="GPString",
parameterType="Required",
direction="Input"
)
bandNums=arcpy.Parameter(
displayName="波段数",
name="bandNums",
datatype="Long",
parameterType="Required",
direction="Input"
)
resultFolder = arcpy.Parameter(
displayName="最终处理结果",
name="resultFolder",
datatype="Folder",
parameterType="Required",
direction="Input"
)
spatialReference=arcpy.Parameter(
displayName="空间参考",
name="spatialReference",
datatype="GPSpatialReference",
parameterType="Optional",
direction="Input"
)
#设置默认值
spatialReference.defaultEnvironmentName = "#"
pixelType=arcpy.Parameter(
displayName="pixelType(Optional)",
name="pixelType",
datatype="GPString",
parameterType="Optional",
direction="Input"
)
pixelType.filter.type = "ValueList"
pixelType.filter.list = ["1_BIT","2_BIT","4_BIT","8_BIT_UNSIGNED","8_BIT_SIGNED","16_BIT_UNSIGNED",
"16_BIT_SIGNED","32_BIT_UNSIGNED","32_BIT_SIGNED","32_BIT_FLOAT","64_BIT"]
pixelType.defaultEnvironmentName = "8_BIT_UNSIGNED"
pixelType.value="8_BIT_UNSIGNED"
mosaicOp=arcpy.Parameter(
displayName="Mosaic Oprator(Optional)",
name="mosaicOp",
datatype="GPString",
parameterType="Optional",
direction="Input"
)
mosaicOp.filter.type = "ValueList"
mosaicOp.filter.list = ["FIRST","LAST","BLEND","MEAN","MINIMUM","MAXIMUM","SUM"]
mosaicOp.defaultEnvironmentName = "LAST"
mosaicOp.value="LAST"
mosaicColormap=arcpy.Parameter(
displayName="Mosaic ColorMap Mode(Optional)",
name="mosaicColormap",
datatype="GPString",
parameterType="Optional",
direction="Input"
)
mosaicColormap.filter.type = "ValueList"
mosaicColormap.filter.list = ["REJECT","FIRST","LAST","MATCH"]
mosaicColormap.defaultEnvironmentName = "FIRST"
mosaicColormap.value="FIRST"
params = [dataFolder,resultFolder,exTension,spatialReference,pixelType,bandNums, mosaicOp,mosaicColormap]
return params
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."""
dataFolder = parameters[0].valueAsText
resultFolder=parameters[1].valueAsText
exTension = parameters[2].valueAsText
spatialReference = parameters[3].valueAsText
pixelType = parameters[4].valueAsText
bandNums = parameters[5].valueAsText
mosaicOp = parameters[6].valueAsText
mosaicColormap = parameters[7].valueAsText
doExcute(dataFolder,resultFolder,exTension,spatialReference,pixelType,bandNums,mosaicOp,mosaicColormap)
return
数据融合代码相对来说比较简单,现在贴一下比较核心的代码段:
# coding:utf-8
import arcpy
import shutil,os
def del_file(path):
ls = os.listdir(path)
for i in ls:
c_path = os.path.join(path, i)
if os.path.isdir(c_path):
del_file(c_path)
else:
os.remove(c_path)
def list_all_files(rootdir):
_files = []
list = os.listdir(rootdir) # 列出文件夹下所有的目录与文件
for i in range(0, len(list)):
path = os.path.join(rootdir, list[i])
if os.path.isdir(path):
_files.extend(list_all_files(path))
if os.path.isfile(path):
_files.append(path)
return _files
def list_all_dir(rootdir):
_files=[]
list=os.listdir(rootdir)
return list
def containVarInString(containVar,stringVar):
try:
if isinstance(stringVar, str):
if stringVar.find(containVar):
return True
else:
return False
else:
return False
except Exception,e:
print e
#http://www.mamicode.com/info-detail-2313739.html
#def doExcute(dataPath,bandNums,resultRoot):
def doExcute(dataFolder, resultFolder, exTension, spatialReference, pixelType, bandNums, mosaicOp, mosaicColormap):
dataPath=dataFolder+"/"
print "结果路径"
print resultFolder
imgArray=[]
listDir=list_all_dir(dataPath)
for row in listDir:
dirFileName=row
tmpFileDir=dataPath+str(dirFileName)
#如果文件存在
if os.path.exists(tmpFileDir):
dataResource=tmpFileDir+"/"+dirFileName
imgArray.append(dataResource);
strDataRoot=""
for item in imgArray:
print item
length=len(imgArray)
for index in range(len(imgArray)):
if index==0:
strDataRoot=imgArray[index]
else:
strDataRoot = strDataRoot + ";" + imgArray[index]
arcpy.MosaicToNewRaster_management(input_rasters=strDataRoot,
output_location=resultFolder,
raster_dataset_name_with_extension=exTension,
coordinate_system_for_the_raster=spatialReference,
pixel_type=pixelType,
cellsize="#",
number_of_bands=bandNums,
mosaic_method=mosaicOp,
mosaic_colormap_mode=mosaicColormap)
至此,整个讲解就说明完了。更多相关arcpy的开发,将需要不断学习。
更多内容,请关注公众号