Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Prints a comparison of the specified raster properties using arcpy and numpy.
#
# @date 25/08/2015
# @author Cindy Williams
#
# Prints a comparison of the specified raster
# properties using arcpy and numpy.
#
# For use as a standalone script.
#
import arcpy as ap
import numpy as np
ext_lyr = ap.management.MakeFeatureLayer(r"") # Extent polygon shapefile/feature class
input_raster = ap.Raster(r"") # Raster containing values
def get_raster_properties(ras, prop):
array = ap.RasterToNumPyArray(ras, nodata_to_value=0)
ap_answer = ap.management.GetRasterProperties(ras, prop)
if prop == "MEAN":
np_answer = array.mean()
if prop == "SUM":
np_answer = array.sum()
if prop == "ROWCOUNT":
np_answer = array.shape[0]
if prop == "COLUMNCOUNT":
np_answer = array.shape[1]
# etc
return (ap_answer, np_answer)
with arcpy.da.SearchCursor(ext_lyr, ("SHAPE@", "Name")) as cursor:
for row in cursor:
# Get the extent of the current feature
ext = row[0].extent
# Build the feature envelope from the extent
enve = "{0} {1} {2} {3}".format(ext.XMin, ext.YMin, ext.XMax, ext.YMax)
# Clip the raster to the envelope in memory
clipped_raster = ap.Raster(ap.management.Clip(input_raster, enve, r"in_memory\clip"))
# Get the properties
(arcpy_ans, numpy_ans) = get_raster_properties(clipped_raster, "MEAN")
print("{0}\tarcpy: {1}\tnumpy: {2}".format(row[1], arcpy_ans, numpy_ans))
# Clean up after each run
ap.management.Delete("in_memory")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment