TransWikia.com

Clipping raster by multiple datasets or polygons?

Geographic Information Systems Asked by Rosie Bell on January 14, 2021

I would like to clip a DEM using a grid of polygons. It’s probably easier to use multiple polygons in one shape file, but I haven’t managed this so I’m trying to use a for loop so I can loop through each dataset in a gdb (each contains only one polygon).

Here’s my code (doing it in the python window).

#creating a workspace and a list of feature classes
arcpy.env.workspace = "C:/data/lidar/lidar.gdb"
fcs = arcpy.ListFeatureClasses()

#looping through each feature class and creating a raster based on the extent of   
#feature class

for fc in fcs:
    arcpy.Clip_management("perth", "#", "C:/data/lidar", fc, "", "ClippingGeometry")

My code doesn’t execute however, it just sits there, waiting for something else… but what? I can get it to work for one clip, but not with the loop.

I’m sure I should be doing something else for the output, to name each new raster by feature class or something… but again, don’t know how. Please let me know if I should add any more info.

3 Answers

One thing I notice is that your third parameter is a hard coded output (C:/data/lidar). The way it's written now will loop through each of your features and overwrite the output every time, but since you may not have allowed the automatic overwriting of files, this could potentially be the hang-up. Try creating a unique output name for each iteration:

#creating a workspace and a list of feature classes
arcpy.env.workspace = "C:/data/lidar/lidar.gdb"
fcs = arcpy.ListFeatureClasses()

#looping through each feature class and creating a raster based on the extent of   
#feature class

i=0
for fc in fcs:
    outputPath = "C:/data/lidar" + str(i)
    i+=1
    arcpy.Clip_management("perth", "#", outputPath, fc, "", "ClippingGeometry")

Also, I'm not certain that you intended to place the outputs in the C:/data folder named lidar... note that the third parameter in clip is the full path of your output raster, not a folder that it will be placed in. If you don't specify an extension in your output path name and place them in a standard folder, it will be a grid, so right now your program is attempting to create a new grid dataset named 'lidar' in the C:/data folder.

Correct answer by bluefoot on January 14, 2021

Here are two options:

  1. Use the built-in ArcGIS tool called Split Raster (Data Management).

    Divides a raster dataset into smaller pieces, by tiles or features from a polygon.

  2. Try the Raster Split Tool, available from the USGS (see attached source code below).

enter image description here

Source code for USGS Raster Split tool:

"""
Raster Split Tool 6/16/2011
ArcGIS 10 Script Tool
Python 2.6.5

Contact:
Douglas A. Olsen
Geographer
Upper Midwest Environmental Sciences Center
U.S. Geological Survey
2630 Fanta Reed Road
La Crosse, Wisconsin 54603
Phone: 608.781.6333
"""
import arcpy
from arcpy import env
import os
from arcpy.sa import *

# Get Shapefile Name
inShape = arcpy.GetParameterAsText(0)
# Get Split Shapfile Name
splitShape = arcpy.GetParameterAsText(1)
# Get Field Name
splitField = arcpy.GetParameterAsText(2)
# Get Output Directory
outDirectory = arcpy.GetParameterAsText(3)
# Get Raster to Split
splitRaster = arcpy.GetParameterAsText(4)
# Get type of output tif, img, or GRID
rasterType = arcpy.GetParameterAsText(5)
# Set Workspace environment
env.workspace = outDirectory

# Run Split command on Input Shapefile
arcpy.Split_analysis(inShape, splitShape, splitField, outDirectory)

# Loop through a list of feature classes in the workspace
for fc in arcpy.ListFeatureClasses():
 
    # Execute ExtractByMask
    rfc = ExtractByMask(splitRaster, fc)

    # Clean up shp file from work directory
    arcpy.Delete_management(fc, "")    
    
    arcpy.AddMessage("Processing: " + fc)
    
    # Replace spaces with underscores
    fc = fc.replace(' ','_')
    
    # Remove .shp suffix
    fc = fc[:-4]
    
    # Trim to 13 chars
    fc = fc[0:13]
    
    if rasterType == 'img':
        fc = fc + "." + rasterType
    elif rasterType == 'tif':
        fc = fc + "." + rasterType
    else:
        print ('No extension')
        
    # Save the output
    rfc.save(fc)

Answered by Aaron on January 14, 2021

for future seekers: Here's a modified version of the USGS raster split tool script that doesn't require anything above the ArcGIS Basic (ArcView) license level:

"""
Raster Split Tool 6/16/2011
ArcGIS 10 Script Tool
Python 2.6.5

Contact:
Douglas A. Olsen
Geographer
Upper Midwest Environmental Sciences Center
U.S. Geological Survey
2630 Fanta Reed Road
La Crosse, Wisconsin 54603
Phone: 608.781.6333

#####
modified 2015-04-15 by Jeremiah Poling ([email protected])
Now using only tools available at the ArcGIS Basic license level 
#####

"""
import arcpy
from arcpy import env
import os

# Get Split Shapfile Name
splitShape = arcpy.GetParameterAsText(0)
# Get Field Name
splitField = arcpy.GetParameterAsText(1)
# Get Output Directory
outDirectory = arcpy.GetParameterAsText(2)
# Get Raster to Split
splitRaster = arcpy.GetParameterAsText(3)
# Get type of output tif, img, or GRID
rasterType = arcpy.GetParameterAsText(4)
# Set Workspace environment
env.workspace = outDirectory

# Loop through the rows in the clipping shapefile
cursor = arcpy.SearchCursor(splitShape)
for row in cursor:
    resultName = row.getValue(splitField)

    # Create feature layer of current clipping polygon
    whereClause = '"' + splitField + '" = ' + "'" + resultName + "'"
    arcpy.MakeFeatureLayer_management(splitShape, 'currentMask', whereClause)

    # Replace spaces with underscores
    resultName = resultName.replace(' ','_')

    # Remove .shp suffix
    if resultName[-4:] == '.shp':
        resultName = resultName[:-4]

    arcpy.AddMessage("Processing: " + resultName)

    if rasterType == 'img':
        resultName = resultName + "." + rasterType
    elif rasterType == 'tif':
        resultName = resultName + "." + rasterType
    else:
        print ('No extension')

    # Save the clipped raster
    arcpy.Clip_management(
        in_raster = splitRaster,
        rectangle = "#",
        out_raster = resultName,
        in_template_dataset = 'currentMask',
        nodata_value="255",
        clipping_geometry="ClippingGeometry",
        maintain_clipping_extent="NO_MAINTAIN_EXTENT"
        )

    if arcpy.Exists('currentMask'):
        arcpy.Delete_management('currentMask')

Answered by Jeremiah Poling on January 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP