[GIS] How to compare two rasters and reclass the greater value(python script)

arcpymap-algebrapythonrasterraster-calculator

I am working on an assignment that requires us to reclass a raster(via python) from two rasters. We need to compare the power received at one cell(on raster1) and compare it to the same cell on raster 2.

If the value of that cell in raster1 is greater than the value in raster2, the cell would be assigned a value of "1" while a value in raster2 greater than raster1 would get a "2". We also need to reclassify certain values as "0" since they are considered out of range.

So the final raster would have three values:
0-out of range/no service
1-better value in raster1
2-better value in raster2

I can try to clarify further if needed.

Best Answer

Assuming you have spatial analyst you can create a difference raster and then follow with a nested Con statement to produce your result.

Activate spatial analyst

if arcpy.CheckExtension("Spatial") == "Available":
    print "Checking out Spatial"
    arcpy.CheckOutExtension("Spatial")
else:
    print "Unable to get spatial analyst extension"
    sys.exit(0)

First load your rasters as raster objects:

Ras2 = raster(r"d:\Some\path\raster.tif")
Ras1 = raster(r"d:\Some\Other\path\OtherRaster.tif")

then subtract and conditional

Diff = Ras2-Ras1
PreResult = Con((Ras2 <= -80) | (Ras1 <= -80) | IsNull(Ras2) | IsNull(Ras1),0,Diff)
Result = Con(PreResult == 0,0,Con(PreResult < 0,1,Con(PreResult > 0,2)))
Result.save(r"d:\Out\Path\OutRaster.tif") # save the raster as a file

The first two IsNull statements in the con cover areas of nodata in both input rasters so if one or the other is nodata the result is 0 then if the difference is 0 it is also 0, less than 0 is 1 and greater than 0 is 2.

Don't forget to free up spatial analyst when you're done: arcpy.CheckInExtension("Spatial")

Reference:

Subtracting rasters http://resources.arcgis.com/en/help/main/10.1/index.html#//005m000000mn000000

isnull http://resources.arcgis.com/en/help/main/10.1/index.html#//009z000000m8000000

con http://resources.arcgis.com/en/help/main/10.1/index.html#//009z00000005000000

Related Question