Sunday 22 May 2016

arcpy - Create conditional to check if raster has value


I have a problem with this code:


ac = ExtractByMask(raster, "area.shp")
arcpy.RasterToPoint_conversion(ac, "point.shp", "VALUE")

The problem is that sometimes the raster has no value. (It's a flow accumulation and the precision of my raster is not enough for what I am asking but that's not the point). So the RasterToPoint can't work.


So my question is:
How can I make a condition like: "if my raster has no value, don't do the RasterToPoint"



Answer




There are several ways to incorporate raster properties into a conditional statement. Here are three methods:


import arcpy, os, numpy

ras = r"C:\path\to\raster.tif"

# Method 1 Using Spatial Analyst
if arcpy.sa.Raster(ras).maximum > 0:
arcpy.RasterToPoint_conversion(ras, r"C:\temp\out.shp", "VALUE")

# Method 2 using the raster properties

if arcpy.GetRasterProperties_management(ras, "MAXIMUM").getOutput(0) > 0:
arcpy.RasterToPoint_conversion(ras, r"C:\temp\out.shp", "VALUE")

# Method 3 Describing the raster via a numpy array
array = arcpy.RasterToNumPyArray(ras)

if numpy.max(array) > 0:
arcpy.RasterToPoint_conversion(ras, r"C:\temp\out.shp", "VALUE")

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...