AnsweredAssumed Answered

NDVI calculation using python: Extracting Bands

Question asked by workshop1 on Apr 8, 2020
Latest reply on Apr 8, 2020 by workshop1

Dear All,
I am trying to calculate NDVI for a list of Landsat images. First i identified the path of the input images and the output results as well. Then I created a loop to read each input raster and trying to extract band 4 and 5 from the raster then calculate the NDVI and finally save the NDVI result of landsat image.
However, I might be doing something not acceptable in extracting bands, and I did search online how to extract a band from an image in python but I could not fixed.
Any help would be highly appreicated. The script is shown below along with the error.

 

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


arcpy.CheckOutExtension("Spatial")

arcpy.env.workspace =r"E:\test\Landsat"
out_workspace =r"E:\test\Results"

# Get a list of grids in the workspace.
rasters = arcpy.ListRasters("","TIF")

for raster in rasters:

    # Set the outputname for each output to be the same as the input.
    output_path = os.path.join(out_workspace,raster)

    #create raster object
    raster_path = os.path.join(arcpy.env.workspace,raster)
    raster_object = arcpy.Raster(raster_path)

    inRaster = (raster_object)
    red = arcpy.sa.Raster(inRaster+'\Band_4')
    NIR = arcpy.sa.Raster(inRaster+'\Band_5')
    # NDVI Calculation
    num = arcpy.sa.Float(NIR-red)
    denom = arcpy.sa.Foat(NIR+red)
    NDVI = arcpy.sa.Divide(num, denom)
    #save it
    #con_raster.save(output_path)
    NDVI.Save(output_path)
    arcpy.CheckInExtension("Spatial")

The errors are:

 

Traceback (most recent call last):
  File "E:\test\NDVI20200404.py", line 24, in <module>
    red = arcpy.sa.Raster(inRaster+'\Band_4')
  File "C:\Program Files (x86)\ArcGIS\Desktop10.7\ArcPy\arcpy\sa\Functions.py", line 4409, in Plus
    in_raster_or_constant2)
  File "C:\Program Files (x86)\ArcGIS\Desktop10.7\ArcPy\arcpy\sa\Utils.py", line 53, in swapper
    result = wrapper(*args, **kwargs)
  File "C:\Program Files (x86)\ArcGIS\Desktop10.7\ArcPy\arcpy\sa\Functions.py", line 4406, in Wrapper
    ["Plus", in_raster_or_constant1, in_raster_or_constant2])
RuntimeError: ERROR 000732: Input Raster: Dataset \Band_4 does not exist or is not supported

Outcomes