0

I am trying to calculate multiple NDVI files from multiple red band files and NIR band files in 2 separated folders with the following code using python:

import arcpy
from arcpy.sa import *

# set workspace
arcpy.env.workspace = r"F:/..."

# set folder paths
folder1 = r"F:/..."
folder2 = r"F:/..."

# loop through each raster in folder1 and folder2
for raster1 in arcpy.ListRasters("TIF", folder1):
    for raster2 in arcpy.ListRasters("TIF", folder2):
        # create raster objects
        ras1 = Raster(folder1 + "/" + raster1)
        ras2 = Raster(folder2 + "/" + raster2)

        # calculate NDVI
        ndvi = ((ras2 - ras1) / (ras2 + ras1))

        # save NDVI raster
        ndvi.save(r"F:/..." + raster1[:-4] + "_ndvi.tif")

The code runs successfully but returns an empty output folder. What could be the reason?

2
  • Have you tried the expression once to make sure it is working?
    – BERA
    Mar 3 at 9:01
  • When I try it I do not receive any error message and the proces is labeld as 0 (finished).
    – Timko99
    Mar 3 at 9:14

1 Answer 1

0

ListRasters returns a list of rasters from the env.workspace. And your wildcard and data types are also wrong. See here for more help with list rasters.

This worked for me but you will need to change the work spaces obviously:

import arcpy
from arcpy.sa import *
import traceback
import sys

arcpy.CheckOutExtension("Spatial")
# set workspace



# set folder paths
folder1 = r"C:\gTemp\tester\f1"
folder2 = r"C:\gTemp\tester\f2"
out_dir = "C:\\gTemp\\tester\\"

# loop through each raster in folder1 and folder2
arcpy.env.workspace = folder1
for raster1 in arcpy.ListRasters():
    arcpy.env.workspace = folder2
    for raster2 in arcpy.ListRasters():
        # create raster objects
        ras1 = Raster(folder1 + "/" + raster1)
        ras2 = Raster(folder2 + "/" + raster2)

        # calculate NDVI
        ndvi = ((ras2 - ras1) / (ras2 + ras1))

        # save NDVI raster
        ndvi.save(out_dir + raster1[:-4] + '_ndvi.tif')
print('done')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.