Skip to content

Instantly share code, notes, and snippets.

@mikepianka
Created February 19, 2020 15:21
Show Gist options
  • Save mikepianka/7f2dcf6a038bd0ed9cef7cc9d7616b83 to your computer and use it in GitHub Desktop.
Save mikepianka/7f2dcf6a038bd0ed9cef7cc9d7616b83 to your computer and use it in GitHub Desktop.
Clip a raster in arcpy with multiple polygons
import os
import arcpy
### add inputs
# the input polygon feature class with the areas of interest to clip
fc = r'c:\working\project.gdb\clip_areas'
# the input raster to be clipped
raster = r'c:\working\project.gdb\some_big_raster'
# the directory for the raster output
outdir = r'c:\working\clipped_rasters'
# output rasters will be named by Filename, change it to your id field
# the script will add the bounding extent attribute fields
fields = ['Filename', 'EXT_MIN_X', 'EXT_MIN_Y', 'EXT_MAX_X', 'EXT_MAX_Y']
### process the raster
# add bounding box attributes for each feature
arcpy.AddGeometryAttributes_management(Input_Features = fc,
Geometry_Properties = 'EXTENT'
)
# clip the raster by each polygon in the feature class
with arcpy.da.SearchCursor(fc, fields) as sc:
for row in sc:
# output will be in tif format
outname = str(row[0]) + '.tif'
# make a string of the polygon bounds to feed to the clipping tool
bounds = str(row[1]) + ' ' + str(row[2]) + ' ' + str(row[3]) + ' ' + str(row[4])
# nodata value will be 666
nodata = 666
# query to select the current feature in the search cursor
expression = "Filename = '" + row[0] + "'"
print('creating ' + outname + '...')
# select the current feature in the search cursor
arcpy.SelectLayerByAttribute_management(fc, 'NEW_SELECTION', expression)
# clip the raster using the current polygon feature's geometry
arcpy.management.Clip(in_raster = raster,
rectangle = bounds,
out_raster = outdir + os.sep + outname,
in_template_dataset = fc,
nodata_value = nodata,
clipping_geometry = 'ClippingGeometry',
maintain_clipping_extent = 'NO_MAINTAIN_EXTENT'
)
print('all done! the output is in ' + outdir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment