Mosaic rasterstacks using minimum of certain layer

397 Views Asked by At

I am trying to mosaic 42 remote sensing rasterstacks (with 250 bands) based on the criterion that in overlapping areas, the pixel should be taken that has the most nadir viewing angle

Beside my rasterstacks I also have 42 rasters (so one for each stack) with the corresponding viewing angle for each pixel.

Any idea how to solve this?

I tried to include the viewing angle raster in the stack, and use something similar to

mosaic(a,b,fun=function(x)(min(x[[251]])) 

but that didn't work...

Any advice?

Thanks in advance,

R.

1

There are 1 best solutions below

2
On

When asking an R question like this, you should set up a simple example with code to better illustrate your problem and to make it easier to answer.

Here is the problem

library(raster)
r <- raster(ncol=100, nrow=100)
r1 <- crop(r, extent(-10, 11, -10, 11))
r2 <- crop(r, extent(0, 20, 0, 20))
r3 <- crop(r, extent(9, 30, 9, 30))

# reflectance values
r1[] <- 1:ncell(r1)
r2[] <- 1:ncell(r2)
r3[] <- 1:ncell(r3)

set.seed(0)
# nadir values
n1 <- setValues(r1, runif(ncell(r1)))
n2 <- setValues(r2, runif(ncell(r2)))
n3 <- setValues(r3, runif(ncell(r3)))

Your question is how to merge/mosaic r based on values in n (when there are overlapping cells with values, use the value of r(i) that that has the highest corresponding value of n(i) ).

Here is a general approach to solve it:

r <- list(r1, r2, r3)
n <- list(n1, n2, n3)

whichmax <- function(x, ...) { 
    ifelse(all(is.na(x)), NA, which.max(x)) 
}

n$fun <- whichmax
# which layer has the highest nadir value?   
m <- do.call(mosaic, n)

q <- list()
for (i in 1:length(r)) {
    y <- r[[i]]
    x <- crop(m, y)
    y[x != i] <- NA
    q[i] <- y
}

M <- do.call(merge, q)