Monday, 4 September 2017

Looping for NDVI in different file paths using R?



I have different bands separated in different file directory.


I used Raster Calculator to calculate NDVI using "NIR1.tif"-"RED1.tif"/"NIR1.tif"+"RED1.tif" as formula.


The link below describes a loop for StackBand which I supposed is a file containing different bands. In my case, I have separate file path for NIR and RED.



Data is named NIR1...NIR2000.tif and RED1...RED2000.tif.


Using Loop for calculating NDVI in R?


I prefer using R but I am having difficulties in calling NIR and RED and putting them in a loop to calculate NDVI.


Below is my code:


library(raster) 
library(rgdal)
NDVI< list.files("C:\\Users\\path\\Desktop\\PET\\sample\\", pattern="*.tif", all.files=F, full.names = FALSE, recursive = TRUE, ignore.case = FALSE)
for (i in 1:length(NDVI))
NDVI <- raster(function(x,y)
(x="NIR"+str(i)+".tif"), (y="red"+str(i)+".tif"), (x-y/x+y)

writeRaster(NDVI,"NDVI", format="GTiff")

I tried to make some revisions in the code.



Answer



First, your formula is not right. You can't use (x-y/x+y)... Is the same than x - (y/x) + y. So correct this first.


I'll create some example data:


library(raster)

r <- raster()


userpath <- '/some/path/'

for (i in 1:2000) {
temp <- setValues(r,sample(x = 0:1000, size = ncell(r), replace = T))
writeRaster(temp, paste0(userpath,'NIR',i,'.tif'))
temp <- setValues(r,sample(x = 0:1000, size = ncell(r), replace = T))
writeRaster(temp, paste0(userpath,'RED',i,'.tif'))
}

Read NIR and RED in different objects:



NIR <- list.files(path = userpath, pattern = 'NIR*.*.tif',full.names = T)
RED <- list.files(path = userpath, pattern = 'RED*.*.tif', full.names = T)

Maybe, depend of rasters name, raster aren't in order when you use list.files(). In my case is something like:


NIR1.tif
NIR10.tif
NIR100.tif
NIR1000.tif
NIR1001.tif


You should extract the index from raster name to prevent undesired results:


i2 <- gsub(pattern = '.*NIR',replacement = '',x = NIR)
i2 <- gsub(pattern = '.tif$',replacement = '',x = i2)
i2 <- as.numeric(i2)

And finally, compute NDVI inside a loop and save rasters:


for (i in i2) {
ndvitemp <- overlay(raster(NIR[i]),raster(RED[i]), fun = function(x,y) (x - y)/(x + y))
writeRaster(ndvitemp, paste0(userpath,'NDVI',i,'.tif'))
}

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...