[GIS] ListRasters based on filename using Arcpy

arcgis-desktoparcpyndvipythonraster

I am trying to create a python script for ArcMap which calculates the ndvi from two raster images for each RGB/NIR pair in a folder. However, I am unsure how to create two raster lists; one which lists only NIR images and the other which lists RGB images. Below is an example of the filename formats of the input images for the automated NDVI calculation.

'TER Jenkins Leroy 36000_Home Farm_Field 1_na_NIR_140825_0-50622.tif'

'TER Jenkins Leroy 36000_Home Farm_Field 1_na_RGB_140825_0-50622.tif'

'TER Jenkins Leroy 36000_Home Farm_Field 2_na_NIR_140825_1-50622.tif'

'TER Jenkins Leroy 36000_Home Farm_Field 2_na_RGB_140825_1-50622.tif'

'TZR Costanza George_Eden_Field 1_na_NIR_140825_2-50648.tif'

'TZR Costanza George_Eden_Field 1_na_RGB_140825_2-50648.tif'

Here is the code I have so far:

import arcpy, os
from arcpy import env
from arcpy.sa import *

env.workspace = r"C:\Users\chester\Documents\Test_Dataset"
outws = r'C:\Users\chester\Documents'
cirlist = arcpy.ListRasters(*CIR*)
rgblist = arcpy.ListRasters(*RGB*)

imagelist = zip(sorted(cirlist), sorted(rgblist))

for i in imagelist:
    name = os.path.join(outws, i + 'NDVI') 
    outras = (Raster(i[0]) - Raster(i[1]))/(Raster(i[0]) + Raster(i[1]))
    outras.save(name)

Best Answer

I prefer using glob.glob() instead of ListRaster, you have more control on the wildcards.

the second point is that you should not need the RGB image, because CIR is usually used to represent Color Infra-Red. So it includes both the red and NIR necessary for the computation of the NDVI.

List = glob.glob(path +"*CIR*")

for im in List:
    print im #just checking you have something
    outndvi = Float(Raster(im+"\\Layer_3")-Raster(im+"\\Layer_2"))/(Raster(im+"\\Layer_3")+Raster(im+"\\Layer_2"))
    outndvi.save(im[:-4]+"ndvi.tif")

Remark :As mentioned in Erica's comment, you should also avoid spaces in the file names.

EDIT : if you need the two rasters, you can also get the corresponding raster with replace()

 imb = im.replace("CIR","CLR")
Related Question