I'm attempting to write a code in Python that will stack 5 band raster images that are all listed sequentially in a folder and then output the stacked images to a new folder. My first instinct was to automate some sort of for loop structure in arcpy with the composite band tool.
I'd like help with the following things:
I'm having issues getting started with the for loop. Any suggestions on how to approach this?
import arcpy
arcpy.env.workspace = ".\\"
outws = "Stacked_Images_Folder"
for rasters in folder:
band1 =
band2 =
band3 =
band4 =
band5 =
arcpy.CompositeBands_management("band1.tif;band2.tif;band3.tif;
band4.tif, band5.tif","stacked_img.tif")
I'm trying to figure out how the script will know to move on to a new image after stacking 5 bands. Do I need to sort the images into separate folders before beginning, or is there a work-around, e.g. the code knows to move on to the next image after reaching 5 bands?
You don't need a for loop to do this if your rasters are all in the same folder:
import arcpy
wd="Y:/" #have this as your directory where all rasters are located
arcpy.env.workspace = wd
raster_list=arcpy.ListRasters("", "tif")
arcpy.CompositeBands_management(raster_list,"stacked_img.tif") #will save output on the same folder specified above.
If you want to save it to a new subdir:
import os
outws = wd+"Stacked_Images_Folder/"
os.makedirs(outws)
arcpy.CompositeBands_management(raster_list, outws + "stacked_img.tif")
Now if you have multiple set of rasters to merge in the same folder that have a common starting file name, such as img1-b1, img1-b2, etc, you can make the entire process work with the following simple implementation:
import arcpy
image_names=["img" + str(s) for s in range(1,143)]
wd="Y:/" #have this as your directory where all rasters are located
arcpy.env.workspace = wd
for image_name in image_names:
print image_name
raster_list=arcpy.ListRasters(image_name+"-*", "tif")
import os
outws = wd+"Stacked_Images_Folder/"
os.makedirs(outws)
arcpy.CompositeBands_management(raster_list, outws + image_name+ "_stacked_img.tif")