[GIS] Multiply Rasters from two subfolders

arcgis-10.1arcpylistpythonraster

I have two subfolders with Rasters named with the same parameters.
I am trying to figure out a way to Loop a multiplication of each raster into a folder with its pair of the other subfolder.
Looks like:.

SubFolder 1 SubFolder2 Result
178056_WGS.tif 178056_Clean.tif 178056_Mlt.tif
178057_WGS.tif 178057_Clean.tif 178056_Mlt.tif
178058_WGS.tif 178058_Clean.tif 178056_Mlt.tif
178059_WGS.tif 178059_Clean.tif 178056_Mlt.tif

Another option is to have all Raster in the same folder (workspace) but it is not at all desirable. Do you have any suggestion to do it in Arcgis 10.1 with Python (arcpy)?

Best Answer

Here is one approach that utilizes the glob module:

  1. Loop through the rasters in one workspace
  2. Within each iteration, extract the basename from each raster
  3. Manipulate the basename to match the raster in the second workspace
  4. Perform the raster calculation

import arcpy, os, glob
arcpy.CheckOutExtension("Spatial")

ws1 = glob.glob(r'C:\temp\workspace\*.tif')
ws2 = glob.glob(r'C:\temp\workspace2\*.tif')
outws = r'C:\temp\workspace3'

for r in ws1:
    basename = os.path.basename(r).split("_")[0]
    r1 = arcpy.sa.Raster(r)
    r2 = arcpy.sa.Raster(os.path.join(ws2, basename + "_Clean.tif"))

    result = r1 * r2
    outname = basename + "_Mlt.tif"

    result.save(os.path.join(outws, outname))
Related Question