Python Toolbox Raster Parameter Error

673
2
04-04-2013 01:30 PM
MikeMacRae
Occasional Contributor III
Hey all, I borrowed a simple script I found online to clip a shapefile from the extent of a raster. It works perfectly from the ArcMap built in python command prompt. I modified is slightly to use in a tool. It's having issues accepting the raster (inraster) in:
extent = arcpy.Raster(inRaster).extent
I get the following error:

    extent = arcpy.Raster(inRaster).extent
TypeError: expected a raster or layer name


I'm using "Raster Layer" as my inRaster parameter type. The raster type I am using is an ERDAS IMAGINE .img file. I'm thinking it must be conflicting with the parameter type and the .img input raster, but I can't figure out what it is. As I mentioned, it worked from the command prompt, just not in the tool. Any suggestions are welcome.

Code is as follows:

import arcpy

inLines = arcpy.GetParameter(0)
inRaster = arcpy.GetParameter(1)
outRaster = arcpy.GetParameter(2)

pnt_array = arcpy.Array()
extent = arcpy.Raster(inRaster).extent
pnt_array.add(extent.lowerLeft)
pnt_array.add(extent.lowerRight)
pnt_array.add(extent.upperRight)
pnt_array.add(extent.upperLeft)

poly = arcpy.Polygon(pnt_array)

arcpy.Clip_analysis(inLines, poly, outRaster)


Thanks,
Mike
Tags (2)
0 Kudos
2 Replies
T__WayneWhitley
Frequent Contributor
Think text is expected input rather than an object, so use GetParameterAsText instead...that is what the raised TypeError means, 'name' is text and GetParameter provided an 'object'.  So your suspicion is correct... 

That should work, but that looks to me to be some relatively old code and I was also curious if this could be done with arcpy simply passing Extent objects or output extent env setting (rather than creating a new geom obj)?

Enjoy,
Wayne
0 Kudos
curtvprice
MVP Esteemed Contributor
GetParameterAsText() is the more general purpose solution, and it's easier to debug as what you get is text so you can print it!

You should use Describe() instead of Raster(), as that will successfully deal with either a raster layer or path to a raster dataset.

Also - Clip_analysis will give you features out, not a raster:

import arcpy

inLines = arcpy.GetParameterAsText(0)
inRaster = arcpy.GetParameterAsText(1)
outLines = arcpy.GetParameterAsText(2)

pnt_array = arcpy.Array()
extent = arcpy.Describe(inRaster).extent
pnt_array.add(extent.XMin)
pnt_array.add(extent.YMin)
pnt_array.add(extent.XMin)
pnt_array.add(extent.YMin)
poly = arcpy.Polygon(pnt_array)
arcpy.Clip_analysis(inLines, poly, outLines)


Also this would work just as well, as Wayne mentioned:

import arcpy
inLines = arcpy.GetParameterAsText(0)
inRaster = arcpy.GetParameterAsText(1)
outLines = arcpy.GetParameterAsText(2)
arcpy.env.extent = inRaster
arcpy.CopyFeatures_management(inLines, outLines)
0 Kudos